2

I would like to run a for loop with multiple variables which run simultaneously and are not nested.

My code is as follows

for (i, j in c(1,2,3), c("a","b","c")){
print(i)
print(j)
}

I would like this to print out

1
a
2
b
3
c

How can I do this?

0

2 Answers 2

3

We can loop through the sequence of the vectors

for(i in seq_along(x1)) {
        print(x1[i])
        print(y1[i])
  }

It is similar to the option of looping using range in python

x = [1, 2, 3]
y = ['a', 'b', 'c']
for i in range(len(x)):
    print(x[i])
    print(y[i])

data

x1 <- 1:3
y1 <- letters[1:3]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I like how it scales to even more variables e.g for(i in seq_along(x1)) {print(x1[i]); print(y1[i]); print(z1) } x1 <- 1:3 y1 <- letters[1:3] z1 <- c("s","t","u")
0

Try mapply:

 mapply(function(x, y) {print(x); print(y)}, x = 1:3, y = letters[1:3])

Map does something similar as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.