[R] Combined variable names

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Dec 1 00:05:03 CET 2004


Tobias Muhlhofer <t.muhlhofer at lse.ac.uk> writes:

> I am trying to define a large number of variables through a loop construct.
> 
> I have my loop variable i being cycled through 1:100 and I would like
> the variables produced by this to be called
> 
> vi (i.e. v1 v2 v3 etc)
> 
> so, for example I'm going:
> 
> for(i in 1:100) {
> 
> <blank> <- a[i:N] # or whatever else you want to put on the right side
> }
> 
> where N is previously defined.
> 
> What goes in for <blank>?

...
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
...

Did you? Not to put too fine a point on it, but this particular
question spurred a lengthy thread over the weekend about how polite
one should be (or not) to people who obviously haven't read the FAQ...

This is Question 7.21, to be precise.

Short answer: use assign(paste(...)) if you must, but you're usually
better off constructing a list, for instance like this:

> a <- 1:5 ; l <- lapply(1:5,function(i) a[i:5])
> l
[[1]]
[1] 1 2 3 4 5

[[2]]
[1] 2 3 4 5

[[3]]
[1] 3 4 5

[[4]]
[1] 4 5

[[5]]
[1] 5



-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list