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

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

问题描述:

我有 3 个数据框,我希望它们写在一个 .csv 文件中,一个在其他文件之上,而不是在同一个表中.因此,一个 csv 文件中有 3 个不同的表.它们都有相同的尺寸.

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.

write.csv 的问题:它不包含append"功能

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

write.table 的问题:来自 write.table 的 csv 文件不像 write.csv 那样被 Excel 2010 很好地读取

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 :

解决方案?

write.csv 只是在幕后调用 write.table ,并带有适当的参数.因此,您可以通过对 write.table 的 3 次调用来实现您想要的.

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)

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

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")