0

I am wondering of how can I loop the multiple variables at the same time in R.

For example,

a = c(1, 2, 3)
b = c(4, 5, 6)

And then for loop, the below code didnt work.

for (i, j in a, b) {
    print(i)
    print(j)
}

In Python,

for i,j in zip(a,b):
  print(i)
  print(j)

it is possible. How can I do this in R?

Clemsang
  • 5,053
  • 3
  • 23
  • 41
user12388610
  • 167
  • 1
  • 11
  • 1
    Does this answer your question? [Zip or enumerate in R?](https://stackoverflow.com/questions/9281323/zip-or-enumerate-in-r) – Clemsang Jan 06 '20 at 14:14

4 Answers4

2

It's not possible using R, in this case the best solution is to iterate over the length of one array and print the value in the position of each array:

a = c(1, 2, 3)
b = c(4, 5, 6)
for(i in 1:length(a))
{
  print(a[i])
  print(b[i])
}
Filipe Lauar
  • 434
  • 3
  • 8
0

In R, it's even simpler:

mapply(function(x,y) print(x,y), a, b)
YOLO
  • 20,181
  • 5
  • 20
  • 40
0

If you want to print all 9 possible combinations, you need to use a nested for loop

a = c(1, 2, 3)
b = c(4, 5, 6)
for(i in 1:length(a))
{
  for(j in 1:length(b))
  {
    print(a[i])
    print(b[j])
  }
}
mckennae
  • 46
  • 3
0

We can use seq_along

for(i in seq_along(a)) {
   print(a[i])
   print(b[i])
  }
akrun
  • 874,273
  • 37
  • 540
  • 662