【问题标题】:Write different data frame in one .csv file with R使用 R 在一个 .csv 文件中写入不同的数据帧
【发布时间】:2013-07-14 16:39:09
【问题描述】:

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

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

write.table 的问题:来自write.table 的 csv 文件无法像来自write.csv 的那些一样被 Excel 2010 漂亮地读取

帖子我已经阅读,但我无法找到解决问题的方法:

解决方案?

【问题讨论】:

标签: r file csv dataframe append


【解决方案1】:

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

【讨论】:

  • 感谢您的回答,但write.table 不是解决方案...我更新了我的问题..请看一下我上传的图片
  • 试试看会发生什么。
【解决方案2】:

我们使用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()

【讨论】:

    猜你喜欢
    • 2014-12-29
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多