使用saveRDS和lapply保存多个对象

时间:2017-04-09 07:28:04

标签: r lapply

我正在尝试编写可以获取对象的函数并单独保存它们。这就是我到目前为止所做的:

# Objects
x = 1:10
y = letters[1:10]
# Save location
folder = "Output_Data"

# Save a single object
ObjSave <- function(object, folder) {
  filename = paste0(folder, "/", deparse(substitute(object)), ".rds")
  saveRDS(object, filename)
}
ObjSave(x, folder)  # Works fine. Output: x.rds

# Save multiple objects
ObjSave <- function(..., folder) {
  invisible(lapply(
    list(...),
    function(object) {
    filename = paste0(folder, "/", deparse(substitute(object)), ".rds")
    saveRDS(object, filename)}
  ))
}
ObjSave(x, y, folder = folder)
# Creates a single object "X[[i]].rds"
# When I use readRDS, it gives the last object i.e. y
# I'm trying to get separate x.rds and y.rds containing x and y respectively

任何帮助将不胜感激!我认为只是deparse(substitute(object))给了我一些问题,但我还没有解决过。

1 个答案:

答案 0 :(得分:1)

解压缩对象时需要小心。

如果您要在功能输入中查找变量名称,则最容易在函数的第一行上执行此操作,否则如果您稍后在更改其功能之后再调用它。 s引用(例如,在lapply循环中)解析树改变,因此解析名称改变。

x = 1:10
y = letters[1:10]
# Save location
folder = "output_data"

# Save multiple objects
ObjSave <- function(..., folder) {
    objects <- list(...)
    object_names <- sapply(substitute(list(...))[-1], deparse)
    sapply(1:length(objects), function(i) {
        filename = paste0(folder, "/", object_names[i], ".rds")
        saveRDS(objects[i], filename)
    })
}
ObjSave(x, y, folder = folder)