r - Iterating with 2 variables in for

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.


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]
  ))

}

Tags:

For Loop

R