Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a new line into an existing csv file [duplicate]

Tags:

r

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.

  • How to append a datatable of same size into an existing csv file?
like image 836
lf_araujo Avatar asked Oct 25 '25 13:10

lf_araujo


1 Answers

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 )
like image 197
bmosov01 Avatar answered Oct 28 '25 03:10

bmosov01