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.
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.
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.
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.
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.
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]
))
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With