write.csv()一个不等大小的data.frames列表

时间:2011-09-08 15:59:16

标签: r

我想将一个data.frame()对象列表输出到csv文件中,以便我可以将其用于演示。我发现它回复了一个错误:

In write.csv(tmp[i], file = "Output.csv", append = T) :
  attempt to set 'append' ignored

我已将输出保存到列表中(所有这些都可以强制转换为df),这是一个例子:

outputs <- list() 
outputs$fivenum <- fivenum(rnorm(100))
outputs$summary <- as.data.frame(as.vector(summary(rnorm(100))))

tmp <- lapply(outputs, as.data.frame)

write.csv(tmp, file="Output.csv",append=T)

每个附加操作都必须具有相同的列数吗?

2 个答案:

答案 0 :(得分:13)

这是一个警告,而不是错误。您无法使用append=FALSE更改write.csv?write.csv说:

  

尝试更改'append','col.names','sep','dec'或'qmethod'   被忽略,并发出警告。

使用write.table代替sep=","

答案 1 :(得分:2)

现在,您可以使用sheetr

在一个CSV中导出多个数据框
install.packages("devtools")
library(devtools)

# Install package from github
install_github('d-notebook/sheetr')
library(sheetr)

# Create a list of dataframes
iris_dataframe = list()
iris_dataframe[["Setosa subset"]] = head(iris[iris$Species == "setosa",])
iris_dataframe[["Versicolor subset"]] = head(iris[iris$Species == "versicolor",])

# Write the list of dataframes to CSV file
write_dataframes_to_csv(iris_dataframe, "exmaple_csv.csv")

将导出:

screenshot


或者,如果您希望手动执行此操作,则可以使用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()