Skip to content

Dynamically build variable names

5 messages · Stefan Petersson, jim holtman, Henrik Bengtsson

#
I'm trying to dynamically build variable names to use on a list. Let's say I have a list like this one:

l <- list(V1_1=c(1,2,3), V1_2=c('One','Two','Three'))

And I succesfully build my variable name like this:

paste('l$', 'V1_1', sep='')

Why can't I just run a mean call with the pasted variable name?

mean(paste('l$', 'V1_1', sep=''))

So, my question is; How do one build variable names dynamically to be able to use them on an R list.

-----------------------------------------------------------------------
R version 2.11.0 (2010-04-22) 
i486-pc-linux-gnu 

locale:
 [1] LC_CTYPE=en_US.utf8          LC_NUMERIC=C                
 [3] LC_TIME=en_US.utf8           LC_COLLATE=en_US.utf8       
 [5] LC_MONETARY=en_US.utf8       LC_MESSAGES=en_US.utf8      
 [7] LC_PAPER=en_US.utf8          LC_NAME=en_US.utf8          
 [9] LC_ADDRESS=en_US.utf8        LC_TELEPHONE=en_US.utf8     
[11] LC_MEASUREMENT=en_US.utf8    LC_IDENTIFICATION=en_US.utf8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] foreign_0.8-40

loaded via a namespace (and not attached):
[1] tools_2.11.0
#
have a list like this one:
use them on an R list.
I found a solution. After three days of banging my head, it just took me three
minutes after I posted. 

mean(unclass(eval(parse(text=paste('d$', 'V1_1', sep='')))))

I have no idea if this is considered 'good R coding'. It works, but I would
appreciate comments never the less...
#
On Mon, May 17, 2010 at 11:12 AM, jim holtman <jholtman at gmail.com> wrote:
...and if the answer is get() or assign() you should usually consider
library("fortunes"); fortune("rethink the question");

/Henrik