I want to add a new row into an existing csv file in the system. Below is a MWE. First, create a data table and write it into file:
date <- "2017-08-01"
investPercent<- 20
expenses <- 20000
savings <- 30000
low <- 10
high <- 20
objective <-19000
data<-data.frame(date, investPercent, expenses, savings, low, high, objective)
write.csv(data, file="./finances.csv", row.names = F)
Now perform the opposite operation and read from the existing file, modify the variables and try to append the modified datatable into the existing file:
data<-read.csv("./finances.csv",stringsAsFactors = FALSE)
date <- Sys.Date()
investPercent<- 99
expenses <- 29999
savings <- 39999
low <- 19
high <- 29
objective <-19999
dataplus<- data.frame(date, investPercent, expenses, savings, low, high, objective)
write.csv(dataplus, file="./finances.csv", append = T)
This does not work, the finances.csv file gets rewritten entirely and the append option seems only to work when the file is a string.
You cannot append using write.csv(). Instead you need to use write.table() and specify a few additional parameters. The following will append a new row of data to your csv file, omitting the column headers for the append. That means you only need to include column headers when you write the table the first time; after that, the data should flow in under the same headers.
write.table( dataplus,
file="./finances.csv",
append = T,
sep=',',
row.names=F,
col.names=F )
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