【发布时间】:2019-09-13 22:45:06
【问题描述】:
【问题讨论】:
-
您可以将其简化为
sum^n_{i = 1} f(x_i, x_n),因为 j \geq n 和 length(x) = n 意味着内部总和是多余的。
【问题讨论】:
sum^n_{i = 1} f(x_i, x_n),因为 j \geq n 和 length(x) = n 意味着内部总和是多余的。
一种快速的方法如下:
假设我们有这个向量:
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)
由于假设我们的函数是乘法,那么我们需要计算和积,即two_by_two的第一列和第二列的点积。为此,我们需要%*% 运算符:
output <- two_by_two[,1] %*% two_by_two[,2]
> output
[,1]
[1,] 2
【讨论】:
见?combn
x <- 0:2
combn(x, 2)
# unique combos
[,1] [,2] [,3]
#[1,] 0 0 1
#[2,] 1 2 2
sum(combn(x, 2))
#[1] 6
combn() 创建所有独特的组合。如果您有要求和的函数,可以在调用中添加FUN:
random_f <- function(x){x[1] + 2 * x[2]}
combn(x, 2, FUN = random_f)
#[1] 2 4 5
sum(combn(x, 2, FUN = random_f))
#[1] 11
【讨论】: