13

I have 3 data frame, and I want them to be written in one single .csv file, one above the others, not in a same table. So, 3 different tables in one csv file. They all have same size.

The problem with write.csv: it does not contain "append" feature

The problem with write.table: csv files from write.table are not read prettily by Excel 2010 like those from write.csv

Here is with <code>write.csv</code>

Here is with <code>write.table</code>

Post I already read and in which I could not find solution to my problem :

Solution ?

Community
  • 1
  • 1
David
  • 4,785
  • 7
  • 39
  • 63
  • Excel can import text files (tab separated/fixed width). See http://office.microsoft.com/en-us/excel-help/import-or-export-text-txt-or-csv-files-HP010342598.aspx – James Pringle Jul 16 '13 at 13:44

2 Answers2

28

write.csv just calls write.table under the hood, with appropriate arguments. So you can achieve what you want with 3 calls to 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)

Actually, you could avoid the whole issue by combining your data frames into a single df with rbind, then calling write.csv once.

write.csv(rbind(df1, d32, df3), "filename.csv")
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
14

We 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