[R] using a list to index elements of a list

William Dunlap wdunlap at tibco.com
Tue Mar 23 16:45:30 CET 2010


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Pj253
> Sent: Tuesday, March 23, 2010 7:54 AM
> To: r-help at r-project.org
> Subject: [R] using a list to index elements of a list
> 
> 
> I have a list of vectors, x, with x[[1]]=1:5, say.
> 
> And I need to go through each element of each vector in a for loop.
> Something like:
> 
> for (v in x[[1]])
> print(v)
> 
> However, I need to store this index "v" for later, and I have 
> lots of other
> indices which we range over later in the code so thought I'd 
> make a list of
> these indices, v<-list(). But then when I try:
> 
> for( v[[1]] in x[[1]] )
> print(v[[1]])
> 
> I get errors:
> 
> > x<-list()
> > x[[1]]=1:5
> > v<-list()
> > for(v[[1]] in x[[1]])
> Error: unexpected '[[' in "for(v[["

The syntax of the for statement is
   for(<name> in <values>) <expr>
where <name> must be a name object, not
a call like v[[i]] or anything else.

Will your code work as you wish if you
replace the "for(v[[1]] in x[[1]]) { ... }"
with the following?
   for(i in x[[1]]) {
      v[[2]] <- i
      ...
   }

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com  

> > print v[[1]]
> Error: unexpected symbol in "print v"
> 
> Can you not use a list in this way, i.e. to store variables 
> to range over in
> a for loop? Can anyone offer a solution?
> 
> Thanks for any help!
> 
> -- 
> View this message in context: 
> http://n4.nabble.com/using-a-list-to-index-elements-of-a-list-
> tp1679184p1679184.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> 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