[R] Problems using save to store NAMED R objects

Duncan Murdoch murdoch.duncan at gmail.com
Fri Nov 13 03:57:40 CET 2015


On 12/11/2015 6:41 PM, Julio Sergio Santana wrote:
> I have to store (in a file) an R object that was created with is name as
> a string of characters, as follows:
>
>     : nn <- "xxx"
>     : assign(nn, 5)
>     : xxx
>     [1] 5
>
> I don't want to store the object nn but the object xxx. I tried the
> following two expressions but none of them worked:
>
>     : save(get(nn), file="f.RData")
>     Error in save(get(nn), file = "f.RData") : object ‘get(nn)’ not found
>
>     : save(eval(nn), file="f.RData")
>     Error in save(eval(nn), file = "f.RData") : object ‘eval(nn)’ not
> found
>
> I know that both save(xxx, ..), and save("xxx", ..) work, but the fact
> is that the string is going to be provided by an user:
>
>     : nn <- readline("Your variable->")
>
> and
>     : save(nn, file="f.RData")
> stores the objet nn not xxx
>
> Do you have any comments on this?

I believe

do.call(save, list(as.name(nn), file = "f.RData"))

should do what you want.  There are probably other ways, maybe simpler 
ones.

If you're interested, the theory here is that do.call() constructs a 
call to the first argument, with arguments found by evaluating the 
second argument.

Duncan Murdoch



More information about the R-help mailing list