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?
You need to use the symbol $ to append dataframe R variable and add a column to a dataframe in R.
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).
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.
Appending Multiple Rows to a DataFrame in R The simplest method here is again to use the rbind() function.
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)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With