2011-09-08 28 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() 
相關問題