My question stems from a previous discussion where I was seeking a solution to append to a .rds file using R. However, as explained at length on this thread: How to append new rows to .RDS file in Rstudio using write() function it is not possible to do that. I am now attempting a workround by first converting the RDS to CSV:
The RDS file has a single column X. I convert the RDS to CSV to allow me to manually add my new record and then convert the CSV back to RDS format, which is the format I need to work with.
Step 1:
> library(foreign)
Step 2: I convert the RDS file to CSV
> for (f in Sys.glob('*.rds'))
write.csv(readRDS(f), file = gsub('rds$', 'csv', f))
Step 3: I insert the new record at the bottom of the CSV file
new_record <- data.frame("D")
write.table(new_record, file = "my_csv_dataframe.csv", append = TRUE, quote = TRUE, col.names = FALSE, row.names = FALSE)
Step 4: I convert the CSV file back to the RDS format
myrdsobject <- read.csv("my_csv_dataframe.csv", header=TRUE)
Step 5: I save as .rds format
saveRDS(myrdsobject, "my_rds_dataframe.rds")
Step 6: I run the below in Rstudio to display my_rds_dataframe.rds and everything looks ok except that the new record, D is written as data.frame instead of D.
> my_rds_dataframe <- read.table("my_rds_dataframe.rds", header=TRUE, quote="\"")
> View(my_rds_dataframe)
As an example after converting the RDS to CSV (Step 2), the output looks as below:
"x"
"A"
"B"
"C"
When I add a record (Step 3) e.g., "D", the resulting CSV is:
"x"
"A"
"B"
"C"
"D"
When I import the RDS file in Rstudio (Step 5) the output appears as:
X
A
B
C
data.frame
Is there anything that I need to do to display the record D in the output instead of data.frame. Unfortunately I am unable to share the actual contents of the original RDS file.
using csv is pointless extra work, once you have the data.frame or matrix object loaded from the rds you grow it in memory by row binding on it with rbind, and then can write out the RDS again.