saveRDS 问题

2024-01-05

我在重新保存对象时表现出了 saveRDS 的奇怪行为。这是一个可重现的示例:

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.

readRDS("test.rds") 中的错误:从连接读取时出错

这有道理吗?这是有意的吗?我可以采取什么措施来避免文件损坏?


编辑:2年后,我无法使用 R 3.6 重现此错误,因此我解决此问题的建议是更新 R。任何可以重现此错误的人请发布您的 R 版本作为评论。


我不知道问题出在哪里,但如果您找不到更好的方法,这里有一个解决方案。在进入 saveRDS 之前,它将返回 str 的错误,因此您不会遇到损坏问题

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

saveRDS 问题 的相关文章

随机推荐