使用函数保存对象属性

时间:2018-03-29 13:13:02

标签: r object attributes save

我正在尝试修改save()函数,以便将发起对象的脚本存储为对象的属性。

s = function(object, filepath, original.script.name){
  #modified save() function
  #stores the name of the script from which the object originates as an attribute, then saves as normal
  attr(object, "original.script") = original.script.name
  save(object, file = filepath)
}

样品:

testob = 1:10
testob
#  [1]  1  2  3  4  5  6  7  8  9 10
s(testob, filepath = "rotation1scripts_v4/saved.objects/testob", "this.is.the.name")
load(file = "rotation1scripts_v4/saved.objects/testob")
testob
#  [1]  1  2  3  4  5  6  7  8  9 10
attributes(testob)
# NULL

进一步调查,似乎没有将对象加载到环境中:

testob2 = 1:5
testob2
# [1] 1 2 3 4 5
s(testob2, "rotation1scripts_v4/saved.objects/testob2", "this.is.the.name")
rm(testob2)
load(file = "rotation1scripts_v4/saved.objects/testob2")
testob2
# Error: object 'testob2' not found

为什么不起作用?

1 个答案:

答案 0 :(得分:0)

您需要小心save()。它保存的变量与传递给save()的名称相同。所以当你打电话给save(object, ...)时,它会将变量保存为“对象”,而不是你想要的“testob”。你可以做一些非标准的环境改组来完成这项工作。尝试

s <- function(object, filepath, original.script.name){
  objectname <- deparse(substitute(object))
  attr(object, "original.script") = original.script.name
  save_envir <- new.env()
  save_envir[[objectname]] <- object
  save(list=objectname, file = filepath, envir=save_envir)
}

我们将deparse(substitute())用于传递给函数的变量的get名称。然后我们创建一个新环境,我们可以在其中创建具有相同名称的对象。这样我们就可以在实际保存对象时使用该名称。

如果我们使用

进行测试,这似乎有效
testob <- 1:10
s(testob, filepath = "test.rdata", "this.is.the.name")
rm(testob)
load(file = "test.rdata")
testob
#  [1]  1  2  3  4  5  6  7  8  9 10
# attr(,"original.script")
# [1] "this.is.the.name"