迭代向量的笛卡尔积 [英] Iterate over cartesian product of vectors
问题描述
我有以下嵌套循环:
for (x in xs) {
for (y in ys) {
# Do something with x and y
}
}
我想要展平,所以我想建立两个向量 xs
和 ys
的笛卡尔积并迭代结果.在 Python 中,这将是微不足道的:
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]
但在 R 中,我发现的最简单的等价物看起来令人生畏:
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.)
推荐答案
您可以使用 apply
函数将函数应用于数据框的每一行.只需将 "your function"
替换为您的实际功能即可.
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]})
<小时>
这是一个使用命名参数 (xs
, ys
) 而不是索引 (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)))
这篇关于迭代向量的笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!