[R] for-loop with multiple variables changing

Peter Dalgaard p.dalgaard at biostat.ku.dk
Mon Feb 6 13:24:34 CET 2006


Sean Davis <sdavis2 at mail.nih.gov> writes:

> On 2/6/06 5:53 AM, "Piet van Remortel" <piet.vanremortel at gmail.com> wrote:
> 
> > Hi all,
> > 
> > Never really managed to build a for-loop with multiple running
> > variables in an elegant way.
> > 
> > Can anybody hint ?
> > 
> > See below for an example of what I would like.
> > 
> > EXAMPLE
> > a<-c(1,2,3)
> > b<-c("name1","name2","name3")
> > 
> > for( number in a, name in b ) {
> > print( number ) ##take a value
> > print( name ) ##and have its name available from a second list
> > }
> > 
> > Does R support this natively ?
> 
> I'm not sure what language does support this construct natively?  In any
> case, what about:

(Genstat has (had?) a "parallel for" structure, I believe.)
 
>  for (j in a) {
>     print(a[j])
>     print(b[j])
>  }

I think you mean "for (i in 1:3) {...}". 

Also, check out the mapply() construct for related functionality.

> You may be thinking of a "hash" structure.  If you are, you could look at
> using lists.  See the R-intro on using list data structures.
> 
> Sean


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907




More information about the R-help mailing list