[R] eval and as.name

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Fri Feb 6 00:05:33 CET 2009


Wacek Kusnierczyk wrote:
> Fuchs Ira wrote:
>   
>> I'm sure there is a more general way to ask this question but how do
>> you use the elements of a character vector as names of objects in an
>> expression?
>> For example, say you have:
>>
>> a = c(1,3,5,7)
>> b = c(2,4,6,8)
>>
>> n=c("a","b")
>>
>> and you want to use the names a and b in a function (e.g. sum)
>>
>> sum(eval(as.name(n[1])),eval(as.name(n[2])))
>>
>> works but
>>
>> what is a simpler way to effect this level of indirection?
>>
>>     
>
> in this particular case, the simplest i can come up with is:
>
> sum(sapply(n, get))
>
> you may want to avoid this sort of indirection by using lists with named
> components:
>
> d = list(a=c(1,3,5,7), b=c(2,4,6,8))
> sum(unlist(d))
> with(d, sum(a+b))
>   
should have been one of

with(d, sum(a,b))
with(d, a+b)

vQ




More information about the R-help mailing list