如何在R中的循环中将多个数据帧写入单个csv文件? [英] how to write multiple dataframe to a single csv file in a loop in R?

查看:226
本文介绍了如何在R中的循环中将多个数据帧写入单个csv文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在单个CSV文件中写入多个数据框"neighbours_dataframe":

我使用这一行将多个数据帧写入多个文件:

for(i in 1:vcount(karate)){
write.csv(neighbours_dataframe[[i]], file = as.character(V(karate3)$name[i]),row.names=FALSE)}

如果我使用此代码:

for(i in 1:vcount(karate)){
write.csv(neighbours_dataframe[[i]], file = "karate3.csv",row.names=FALSE)}

这只会给我csv文件中的最后一个数据帧:

我想知道,我怎么能拥有一个包含所有数据帧的CSV文件,而第一个数据帧的列标题刚刚写入了csv文件,而所有其他数据帧以连续的方式复制了呢?

先谢谢您

解决方案

两个方法;如果neighbours_dataframe是一个很长的列表,第一个可能会更快一些(尽管我还没有对此进行测试).

方法1:首先将数据帧列表转换为单个数据帧

如jbaums所建议.

library(dplyr)
neighbours_dataframe_all <- rbind_all(neighbours_dataframe)
write.csv(neighbours_dataframe_all, "karate3.csv", row.names = FALSE)

方法2:使用循环,追加

如尼尔·富尔茨(Neal Fultz)所建议.

for(i in seq_along(neighbours_dataframe))
{
  write.table(
    neighbours_dataframe[[i]], 
    "karate3.csv", 
    append    = i > 1, 
    sep       = ",", 
    row.names = FALSE,
    col.names = i == 1
  )
}

I would like to write a multiple dataframe "neighbours_dataframe" in a single CSV file :

I use this line to write the multiple dataframe to multiple file :

for(i in 1:vcount(karate)){
write.csv(neighbours_dataframe[[i]], file = as.character(V(karate3)$name[i]),row.names=FALSE)}

if I use this code:

for(i in 1:vcount(karate)){
write.csv(neighbours_dataframe[[i]], file = "karate3.csv",row.names=FALSE)}

this would give me just the last dataframe in the csv file :

I was wondering , How could I have a single CSV file which have all the dataframe in the way that the column header of the first dataframe just written to the csv file and all other data frame copied in a consecutive manner ?

thank you in advance

解决方案

Two methods; the first is likely to be a little faster if neighbours_dataframe is a long list (though I haven't tested this).

Method 1: Convert the list of data frames to a single data frame first

As suggested by jbaums.

library(dplyr)
neighbours_dataframe_all <- rbind_all(neighbours_dataframe)
write.csv(neighbours_dataframe_all, "karate3.csv", row.names = FALSE)

Method 2: use a loop, appending

As suggested by Neal Fultz.

for(i in seq_along(neighbours_dataframe))
{
  write.table(
    neighbours_dataframe[[i]], 
    "karate3.csv", 
    append    = i > 1, 
    sep       = ",", 
    row.names = FALSE,
    col.names = i == 1
  )
}

这篇关于如何在R中的循环中将多个数据帧写入单个csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆