I have the following nested loop:
for (x in xs) {
for (y in ys) {
# Do something with x and y
}
}
Which I’d like to flatten
You can use the apply function to apply a function to each row of your data frame. Just replace "your function" with your actual function.
# example data
xs <- rnorm(10)
ys <- rnorm(10)
apply(expand.grid(xs, ys), 1, FUN = function(x) {"your function"})
This is a very basic example. Here, the sum of both values in a row is calculated:
apply(expand.grid(xs, ys), 1, FUN = function(x) {x[1] + x[2]})
Here is a variant that uses named arguments (xs, ys) instead of indices (x[1], x[2]):
myfun <- function(xs, ys) xs + ys
arguments <- expand.grid(xs = rnorm(10), ys = rnorm(10))
apply(arguments, 1, function(x)do.call(myfun, as.list(x)))