Abhishek Nigam
Abhishek Nigam

Reputation: 43

Updating the CSV file after export using R

I need to update the CSV file after exporting through R.I have managed to export the dataset into a CSV file but I want to retain the existing observations and append the new ones without replacing the CSV file. Below is the code snippet which has a final dataset called "result" and it is replaced every time the query runs. -

  result <- sqldf(query)

  if (!file.exists("final_table.csv"))        
  load(file="final_table.csv")
  write.csv(result, file = 'final_table.csv')

Every time the dataset "result" gets updated, I see a new CSV (final_table) every time I.All I want is one single CSV file that gets updated and the observations are appended.Please suggest me if its possible.

Upvotes: 1

Views: 2521

Answers (1)

r.bot
r.bot

Reputation: 5424

As mentioned by Thomas, append in write.table will sort this for you.

result <- data.frame(x= 2, y = "b")

write.table(result, file = 'final_table.csv', append = TRUE, row.names = FALSE, 
            col.names = FALSE, quote = TRUE, sep = ",")
check <- read.csv("final_table.csv")
check
>   x y
> 1 1 a
> 2 2 b

Upvotes: 2

Related Questions