[R] iterating through for loop

William Dunlap wdunlap at tibco.com
Fri Feb 3 17:25:04 CET 2012


Use a common subscript to go through two or more objects in
parallel:
  > x<-c(1,2,4,7,34,6)
  > y<-c(3,5,6,9,34,7)
  > stopifnot(length(x)==length(y))
  > for(i in seq_along(x)) {
  +    print(paste(x[i], y[i]))
  + }
  [1] "1 3"
  [1] "2 5"
  [1] "4 6"
  [1] "7 9"
  [1] "34 34"
  [1] "6 7"

For this toy example it is easier to just compute
  paste(x, y)
but I assume you plan on doing something more
substantial that isn't already vectorized.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of sagarnikam123
> Sent: Friday, February 03, 2012 1:32 AM
> To: r-help at r-project.org
> Subject: [R] iterating through for loop
> 
> how to iterate two elements each through for loop?
> e.g. x<-c(1,2,4,7,34,6)
> y<-c(3,5,6,9,34,7)
> 
> for(z in x){
> print(paste(z,y))  }
> 
> 
> i want both element of vector iterate serially with same position
> 
> 
> --
> View this message in context: http://r.789695.n4.nabble.com/iterating-through-for-loop-
> tp4354101p4354101.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