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 so I thought of building a Cartesian product of the two vectors xs and ys and iterating over the result. In Python, this would be trivial:
for xy in product(xs, ys):
# x, y = xy[0], xy[1]
But in R, the simplest equivalent I’ve found looks daunting:
xys <- expand.grid(xs, ys)
for (i in 1 : nrow(xys)) {
xy <- as.vector(xys[i, ])
# x <- xy[1], y <- xy[2]
}
Surely there must be a better way, no? (To clarify, I don’t want to iterate over an index … I think there must be a way to directly iterate over the tuples in the product.)
You can use the
applyfunction to apply a function to each row of your data frame. Just replace"your function"with your actual function.This is a very basic example. Here, the sum of both values in a row is calculated:
Here is a variant that uses named arguments (
xs,ys) instead of indices (x[1],x[2]):