9

I would like to pump out a list of data.frame() objects to a csv file so I can work on it for presentation. I'm finding that it's replying with an error:

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

I've saved the outputs to a list (all of which can be coerced to a df), here's an example:

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)

Does every append action have to have the same number of columns?

Brandon Bertelsen
  • 43,807
  • 34
  • 160
  • 255
  • Yes, if you use `write.csv`. I think you can get round this by using `write.table(..., sep=",", append=TRUE`) - but I haven't tested this recently. – Andrie Sep 08 '11 at 16:03
  • 1
    @Andrie: you can't append with `write.csv` ever. Just like you can't change `col.names`, `sep`, `dec`, or `qmethod`. – Joshua Ulrich Sep 08 '11 at 16:23
  • @JoshuaUlrich That's what I thought I said, but clearly the meaning was lost in translation. – Andrie Sep 08 '11 at 16:39
  • @Andrie: I thought you were answering "does every append action have to have the same number of columns?". You can still append even if the objects don't have to have the same number of columns, but that creates a funky file. – Joshua Ulrich Sep 08 '11 at 16:47
  • 3
    Why not rbind.fill them together first? – hadley Sep 09 '11 at 03:25

2 Answers2

13

That's a warning, not an error. You can't change append=FALSE with write.csv. ?write.csv says:

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

Use write.table with sep="," instead.

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
5

You can now export multiple dataframes in a single CSV using 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")

Which will export:

screenshot

.
.

Or, if you prefer to do that manually, you can use sink files:

# 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()
Deena
  • 5,925
  • 6
  • 34
  • 40