Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a whole dataframe to a CSV in R

Tags:

dataframe

r

csv

I can already append a row to a CSV using cat which makes that very easy:

  cat("my row, 1, 2, 3, 4", "mydf.csv",sep="\n", append=TRUE)

However as far as I know you cannot use cat with a whole dataframe (multiple columns and rows).

I am doing this because I am writing many DFs to a CSV and I want to append the multiple CSVs using write.table. The dataframes all have the same number of columns.

I thought about doing a loop over rows to write with cat but that doesn't sound like the best way - any one have good way of doing this in R?

like image 928
Nima Avatar asked Aug 21 '14 22:08

Nima


People also ask

How do I append a DataFrame in R?

You need to use the symbol $ to append dataframe R variable and add a column to a dataframe in R.

How do I append a row to an existing CSV file in Python?

Open your CSV file in append mode Create a file object for this file. Pass the file object and a list of column names to DictWriter() You will get an object of DictWriter. Pass the dictionary as an argument to the writerow() function of DictWriter (it will add a new row to the CSV file).

How do I append rows and columns in a data frame in R?

To add row to R Data Frame, append the list or vector representing the row, to the end of the data frame. nrow(df) returns the number of rows in data frame. nrow(df) + 1 means the next row after the end of data frame. Assign the new row to this row position in the data frame.

Which R function appends Dataframes?

Appending Multiple Rows to a DataFrame in R The simplest method here is again to use the rbind() function.


2 Answers

Ok so I realised that append=T does work with write.table - but write.table needs the sep switch to be used so this works:

write.table(myDF, "myDF.csv", sep = ",", col.names = !file.exists("myDF.csv"), append = T)
like image 165
Nima Avatar answered Sep 29 '22 10:09

Nima


Another workaround (using cat) is that you transpose your data frame, then append a row containing only "\n" using rbind, then converting this data frame to a vector (it will have "\n" after every 'row') which will now show up in your csv file as a data frame.

Below an example:

df <- rbind(t(df),"\n")
cat(c("",df),sep=",",append=TRUE)

Note: my assumption is that you have opened a connection to a file using sink(filepath/filename.csv).

like image 22
Max Avatar answered Sep 29 '22 10:09

Max