简体   繁体   English

如何在R中的循环中将多个数据帧写入单个csv文件?

[英]how to write multiple dataframe to a single csv file in a loop in R?

I would like to write a multiple dataframe "neighbours_dataframe" in a single CSV file : 我想在单个CSV文件中写入多个数据框“ neighbours_dataframe”:

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 : 这只会给我csv文件中的最后一个数据帧:

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 ? 我想知道,如何有一个CSV文件,其中所有数据帧的方式都像第一个数据帧的列标题刚刚写入到csv文件中,而所有其他数据帧以连续方式复制一样?

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). 如果neighbours_dataframe是很长的列表,则第一个可能会更快一些(尽管我尚未对此进行测试)。

Method 1: Convert the list of data frames to a single data frame first 方法1:首先将数据帧列表转换为单个数据帧

As suggested by jbaums. 如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 方法2:使用循环,附加

As suggested by Neal Fultz. 正如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
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM