Skip to content

iterating through for loop

3 messages · sagarnikam123, PIKAL Petr, William Dunlap

#
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.
#
Hi
Not sure what the result shall be. but

paste(x,y)

and

do.call(paste, lapply(expand.grid(x,y), paste))

is what comes to my mind.

If you want something else please follow rules suggested in posting guide.

Regards
Petr
http://www.R-project.org/posting-guide.html
#
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