I'm looking for a way to save()
a variable under a different name "on the fly" in R (bear with me! I'm pretty sure that's not a duplicate...). Here is an example of what I'd like to achieve:
AAA = 1
BBB = 2
XXX = 3
YYY = 4
save(AAA=XXX, BBB=YYY, file="tmp.Rdat")
# does NOT save a variable AAA to file with value 3 in it, which is the aim...
Basically I would like the save()
function to take the value of XXX
and save it to file under a variable named AAA
. Note that this is not a question about renaming a variable: I could of course rename the variable XXX
prior to saving, e.g. AAA = XXX
and then save(AAA, ..., file=...)
but this would of course mess up with the value of AAA
in the rest of the code.
The obvious way is to create temporary variables and then restore the values:
AAA = 1
BBB = 2
XXX = 3
YYY = 4
AAAtmp = AAA; BBBtmp = BBB # record values of AAA, BBB
AAA = XXX; BBB = YYY
save(AAA, BBB, file="tmp.Rdat")
AAA = AAAtmp; BBB = BBBtmp # restore values of AAA, BBB
... but everyone will agree that this is quite messy (especially with many more variables).
This has been bugging me for a while, and my feeling is that the function save()
can't do what I want. So I guess I will have to update my code and go down the path of using a different saving function (e.g. saveRDS()
).
Thanks for the help!
This proved to be a little trickier that I expected. I'll be interested to see what others come up with, and also what any objections to my solution may be.
saveit <- function(..., file) {
x <- list(...)
save(list=names(x), file=file, envir=list2env(x))
}
foo <- 1
saveit(bar=foo, file="hi.Rdata")
A bit quicker than defining a function for the job, you can create a local
environment:
local({
AAA <- XXX
BBB <- YYY
save(AAA, BBB, file="tmp.Rdat")
})
Because you are working and assigning to a different environment, you don't need to store temporary variables that will still be intact in the global environment:
> AAA
[1] 1
> BBB
[1] 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With