Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

r - Iterating with 2 variables in for

Tags:

for-loop

r

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.

like image 634
Rama Avatar asked Jun 08 '15 09:06

Rama


People also ask

Can you have a for loop with two variables?

Yes, I can declare multiple variables in a for-loop. And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas. Do not forget to end the complete initialization statement with a semicolon.

Can you put a for loop in a for loop R?

In Nested For Loop in R, R makes use of the control structures to manage the execution of the expression, one such control structure is Nested For Loop a similar to basic 'for' loop executes.

Can you have two variables in a for loop Java?

In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.

Is apply faster than for loop R?

The apply functions (apply, sapply, lapply etc.) are marginally faster than a regular for loop, but still do their looping in R, rather than dropping down to the lower level of C code. For a beginner, it can also be difficult to understand why you would want to use one of these functions with their arcane syntax.


2 Answers

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

}
like image 136
Werner Avatar answered Sep 29 '22 12:09

Werner


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.

like image 32
Zhaochen He Avatar answered Sep 29 '22 12:09

Zhaochen He