[R] Dynamically build variable names

Henrik Bengtsson hb at stat.berkeley.edu
Mon May 17 11:51:48 CEST 2010


On Mon, May 17, 2010 at 11:12 AM, jim holtman <jholtman at gmail.com> wrote:
> ?'[['
>
> What I think you want is:
>
> x <- "V1_1"
> mean(l[[x]])
>
> Also you need to look at 'get'.

...and if the answer is get() or assign() you should usually consider
library("fortunes"); fortune("rethink the question");

/Henrik

>
> On Mon, May 17, 2010 at 4:41 AM, Stefan Petersson <
> stefan.petersson at inizio.se> wrote:
>
>>
>> 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.
>>
>> -----------------------------------------------------------------------
>> > sessionInfo()
>> 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
>>
>> ______________________________________________
>> 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<http://www.r-project.org/posting-guide.html>
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>
>
> --
> Jim Holtman
> Cincinnati, OH
> +1 513 646 9390
>
> What is the problem that you are trying to solve?
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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