1

I'm trying to modify the save() function so that the script from which the object originated is stored as an attribute of the object.

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)
}

Sample:

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

Investigating further, it seems that the object is not being loaded into the environment:

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

Why isn't it working?

MrFlick
  • 195,160
  • 17
  • 277
  • 295
Thistle19
  • 37
  • 5
  • When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. How exactly are you calling this function? How are you verifying that the attributes are not preserved? – MrFlick Mar 29 '18 at 14:01
  • Hi MrFlick, see updated post for example. Thanks – Thistle19 Mar 29 '18 at 17:38

1 Answers1

0

You need to be careful with save(). It saves variables with the same name that's passed to save(). So When you call save(object, ...), it's saving the variable as "object" and not "testob" which you seem to be expecting. You can do some non-standard environment shuffling to make this work though. Try

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)
}

We use deparse(substitute()) to the get name of the variable passed to the function. Then we create a new environment where we can create the object with the same name. This way we can use that name when actually saving the object.

This appears to work if we test with

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"
MrFlick
  • 195,160
  • 17
  • 277
  • 295