最佳答案
一种快速的方法是:
假设我们有这个向量:
x = c(0,1,2)
即
n=3
,并假设 f 是一个乘法函数:现在,我们使用
expand.grid.unique
custom function在向量内产生独特的组合;换句话说,它类似于 expand.grid
基本功能,但具有独特的组合:expand.grid.unique <- function(x, y, include.equals=FALSE)
{
x <- unique(x)
y <- unique(y)
g <- function(i)
{
z <- setdiff(y, x[seq_len(i-include.equals)])
if(length(z)) cbind(x[i], z, deparse.level=0)
}
do.call(rbind, lapply(seq_along(x), g))
}
在我们的向量案例中,当我们调用
expand.grid.unique(x,x)
时,它产生以下结果:> expand.grid.unique(x,x)
[,1] [,2]
[1,] 0 1
[2,] 0 2
[3,] 1 2
让我们分配
two_by_two
给它:two_by_two <- expand.grid.unique(x,x)
由于我们的函数被假定为乘法,那么我们需要计算 sum-product,即
two_by_two
的第一列和第二列的点积。 .为此,我们需要 %*%
运算符(operator):output <- two_by_two[,1] %*% two_by_two[,2]
> output
[,1]
[1,] 2
关于r - 双和计算,最有效的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57931101/