Rama
Rama

Reputation: 1069

r - Iterating with 2 variables in for

Is there a construct in R where we can iterate with two variables at the same time in R? Like so,

for(i in list1 and j in list2)

The list1 and list2 can be any iterable.

Upvotes: 14

Views: 21946

Answers (3)

Zhaochen He
Zhaochen He

Reputation: 660

There's also the foreach package:

library(foreach)
foreach(i = letters, j = LETTERS) %do% {
  paste(i,j)
}

[[1]]
[1] "a A"

[[2]]
[1] "b B"

[[3]]
[1] "c C"
etc...

This also has the advantage of being easy to parallelize: simply change the %do% to %dopar%, register a parallel back-end, and rock and roll.

Upvotes: 12

Werner
Werner

Reputation: 15065

In general, iterating over multiple variables (of the same length) is best achieved using a single index that acts as an index for referencing elements (variables) in a list:

var_list <- list(
  var1 = 1:10,          # 1, ..., 10
  var2 = letters[17:26] # q, ..., z
)

for (i in 1:length(var_list$var1)) {

  # Process each of var1 and var2
  print(paste(
    'var1:', var_list$var1[i],
    '; var2:', var_list$var2[i]
  ))

}

Upvotes: 11

Karolis Koncevičius
Karolis Koncevičius

Reputation: 9656

If the contents of your for loop can be written as some kind of a function then you can use mapply.

a <- 1:10
b <- LETTERS[1:10]

a
[1]  1  2  3  4  5  6  7  8  9 10
b
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"

mapply(paste, a, b)
[1] "1 A"  "2 B"  "3 C"  "4 D"  "5 E"  "6 F"  "7 G"  "8 H"  "9 I"  "10 J"

Sure you will have to replace "paste" with a function that takes 2 elements (one from each list) as input. Also using more than 2 lists/vectors is ok.

Upvotes: 11

Related Questions