2011-09-08 29 views
8

我想将data.frame()对象的列表抽出到一个csv文件中,以便我可以将它用于演示。我发现它是一个错误回答:write.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) 

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

+0

是的,如果你使用'write.csv'。我想你可以通过使用'write.table(...,sep =“,”,append = TRUE')来解决这个问题 - 但我最近没有测试过。 – Andrie

+1

@Andrie:你不能追加'write.csv'。就像你不能改变'col.names','sep','dec'或'qmethod'一样。 –

+0

@JoshuaUlrich这就是我认为我所说的,但显然在翻译中失去了意义。 – Andrie

回答

13

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

Attempts to change ‘append’, ‘col.names’, ‘sep’, ‘dec’ or ‘qmethod’ are ignored, with a warning.

使用write.tablesep=","来代替。

+0

啊,谢谢Josh,完全错过了那一个。 –

+0

+1是的,这就是我在对主要问题的评论中想到的。 – Andrie

+0

是否有解决方法?我有几个客户喜欢在Excel中获得东西。所以我需要抽出一个excel输出文件(在单元格中有元素而不是在第一个单元格中,并且不得不将文本转换为列) –

1

现在可以使用sheetr

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

这将导出在一个CSV多个dataframes:

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() 
相关问题