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

时间:2013-07-16 13:15:33

标签: r file csv dataframe append

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

write.csv的问题:它不包含“追加”功能

write.table的问题:来自write.table的csv文件不会被Excel 2010与write.csv

中的文件一起阅读

Here is with <code>write.csv</code>

Here is with <code>write.table</code>

发布我已经阅读过了,我无法找到解决问题的方法:

解决方案?

2 个答案:

答案 0 :(得分:17)

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)

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

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

答案 1 :(得分:11)

我们使用sink个文件:

# Sample dataframes:
df1 = iris[1:5, ]
df2 = iris[20:30, ]

# Start a sink file with a CSV extension
sink('multiple_df_export.csv')

 # Write the first dataframe, with a title and final line separator 
cat('This is the first dataframe')
write.csv(df1)
cat('____________________________')

cat('\n')
cat('\n')

# Write the 2nd dataframe to the same sink
cat('This is the second dataframe')
write.csv(df2)
cat('____________________________')

# Close the sink
sink()
相关问题