[R] list of symbols to substitution

Michael Spiegel michael.m.spiegel at gmail.com
Wed Sep 16 15:54:15 CEST 2009


Ah whoops (and thank you).  I forgot to mention an additional
constraint: I'm trying to use exactly one eval statement.  Some
background information on this constraint.  Some of the expressions
that are being evaluated may return an error.  At the moment, I'm
wrapping each of the individual expressions inside a try-catch block
and an eval statement.  I was hoping to find a solution that uses a
single try-catch block and a single eval statement.  Today I realize
that a partial solution is to use a single try-catch block and
multiple eval statements, as has been suggested.  Here is the code
snippet, slightly updated:

symnames <- c('foo', 'bar', 'baz')
foo <- expression(1 + 2)
bar <- expression(3 + 4)
baz <- expression(abs('c'))
expr <- substitute(expr, list(expr = lapply(symnames, as.symbol)))
eval(expr)

Anybody know of a solution that uses a single eval expression?

--Michael

On Wed, Sep 16, 2009 at 1:31 AM, Schalk Heunis
<schalk.heunis at enerweb.co.za> wrote:
> Instead of eval(expr), use lapply(expr,eval)
> HTH
> Schalk Heunis
>
>
> On Wed, Sep 16, 2009 at 5:50 AM, Michael Spiegel
> <michael.m.spiegel at gmail.com> wrote:
>>
>> Hi,
>>
>> I'm trying to use a list of symbols as one of the values to be
>> substituted in a substitute expression, but I can't figure out how to
>> write the correct expression for my problem.  Let me illustrate a
>> simple example of what I'm trying to do.  The following code snippet
>> will evaluate to '5':
>>
>> symname <- 'foo'
>> foo <- 5
>> expr <- substitute(c(expr), list(expr = as.symbol(symname)))
>> eval(expr)
>>
>> I would like the next similar example to evaluate to the list('5',
>> '6', '7'), but instead it evaluates to the list(foo, bar, baz) where
>> the type of foo, bar, and baz are all symbols.  For the purposes of
>> finding a solution assume that the length and contents of symnames are
>> unknown ahead of time (symname is not a constant, assume it is some
>> parameter to a function).
>>
>> symnames <- c('foo', 'bar', 'baz')
>> foo <- 5
>> bar <- 6
>> baz <- 7
>> expr <- substitute(expr, list(expr = lapply(symnames, as.symbol)))
>> eval(expr)
>>
>> Thanks!
>> --Michael
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> 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.
>
>




More information about the R-help mailing list