且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用R在一个.csv文件中写入不同的数据帧

更新时间:2023-10-15 17:45:52

write.csv 只需调用 write.table 所以你可以通过3次调用 write.table 来实现你想要的。

  write.table(df1,filename.csv,col.names = TRUE,sep =,)
write.table(df2,filename.csv,col.names = FALSE,sep = ,,append = TRUE)
write.table(df3,filename.csv,col.names = FALSE,sep =,,append = TRUE)
$ p>

实际上,你可以通过将你的数据帧与rbind组合成一个df,然后调用write.csv一次来避免整个问题。

  write.csv(rbind(df1,d32,df3),filename.csv)


I have 3 data frame, and I want them to be written in one single .csv file, one above the others, not in a same table. So, 3 different tables in one csv file. They all have same size.

The problem with write.csv: it does not contain "append" feature

The problem with write.table: csv files from write.table are not read prettily by Excel 2010 like those from write.csv

Post I already read and in which I could not find solution to my problem :

Solution ?

write.csv just calls write.table under the hood, with appropriate arguments. So you can achieve what you want with 3 calls to write.table.

write.table(df1, "filename.csv", col.names=TRUE, sep=",")
write.table(df2, "filename.csv", col.names=FALSE, sep=",", append=TRUE)
write.table(df3, "filename.csv", col.names=FALSE, sep=",", append=TRUE)

Actually, you could avoid the whole issue by combining your data frames into a single df with rbind, then calling write.csv once.

write.csv(rbind(df1, d32, df3), "filename.csv")