【问题标题】:double sum calculation, what is the most efficient approach?双和计算,最有效的方法是什么?
【发布时间】:2019-09-13 22:45:06
【问题描述】:

我需要计算一下

其中 x 是长度为 n 的向量,f 是函数。

R 中对此最有效的计算是什么?

一种方法是双 for 循环,但这显然很慢。

【问题讨论】:

  • 您可以将其简化为 sum^n_{i = 1} f(x_i, x_n),因为 j \geq n 和 length(x) = n 意味着内部总和是多余的。

标签: r loops


【解决方案1】:

一种快速的方法如下:

假设我们有这个向量:

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

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2011-01-26
      • 2011-07-13
      • 2012-08-14
      • 1970-01-01
      • 2010-09-06
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      • 2018-12-07
      相关资源
      最近更新 更多