Problem with saveRDS

I found the strange behavior of saveRDS when saving an object. Here is an example of reproducibility:

df <- data.frame(a = c(1,2), b = c(3,4))
saveRDS(df, "test.rds") 
readRdsFile <- readRDS("test.rds")
saveRDS(df1, "test.rds") #trying to resave the object however there is an issue with the object df1. Mistaken object name or it has not been compiled somewhere in the code before so it does not exist.
readRdsFile2 <- readRDS("test.rds") #the original file is corrupted.

Error in readRDS ("test.rds"): reading error from connection

It makes sense? Is this the goal and what can I do to avoid file corruption?
+4
source share
1 answer

Change: 2 years later, I can’t reproduce this error with R 3.6, so I suggest fixing it to update R. Anyone who can reproduce the error, please post your version of R as a comment.


I don’t know where the problem came from, but if you do not find anything better, here is the solution. Before returning to saveRDS, it will return an error for str, so you will not have a problem with damage

saveRDS2 <- function(object,file){str(object);saveRDS(object,file)}
df <- data.frame(a = c(1,2), b = c(3,4))
saveRDS2(df, "test.rds") 
readRdsFile <- readRDS("test.rds")
saveRDS2(df1, "test.rds") # error as df1 doesn't exists
readRdsFile2 <- readRDS("test.rds") #the original file is not corrupted and can be reloaded
+2

Source: https://habr.com/ru/post/1678869/


All Articles