3

This is calling for some "tricky R", but this time it's beyond my fantasy :-) I need to save() an object whose name is in the variable var. I tried:

save(get(var), file = ofn)
# Error in save(get(var), file = ofn) : object ‘get(var)’ not found

save(eval(parse(text = var)), file = ofn)
# Error in save(eval(parse(text = var)), file = ofn) : 
#  object ‘eval(parse(text = var))’ not found

both of which fail, unfortunatelly. How would you solve this?

1
  • I usually do, but in this case I thought it's so simple it isn't necessary. Commented Nov 21, 2019 at 15:26

2 Answers 2

8

Use the list argument. This saves x in the file x.RData. (The list argument can specify a vector of names if you need to save more than one at a time.)

x <- 3
name.of.x <- "x"
save(list = name.of.x, file = "x.RData")

# loading x.RData to check that it worked
rm(x)
load("x.RData")
x
## [1] 3

Note

Regarding the first attempt in the question which attempts to use get we need to specify the name rather than its value so that attempt could use do.call converting the character name to a name class object.

do.call("save", list(as.name(name.of.x), file = "x.RData"))

Regarding the second attempt in the question which uses eval, to do that write out the save, substitute in its name as a name class object and then evaluate it.

eval(substitute(save(Name, file = "x.RData"), list(Name = as.name(name.of.x))))
Sign up to request clarification or add additional context in comments.

1 Comment

wow, amazing! I was looking at ?save but I totally missed this argument! Thanks!
0

If it's just one object, you can use saveRDS:

a<-1:4
var<-"a"
saveRDS(get(var),file="test.R")
readRDS(file="test.R")
[1] 1 2 3 4

1 Comment

thanks, but this creates some different format than .Rdata. I prefer to stay with .Rdata.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.