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

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to