双和计算,最有效的方法是什么?

Jan*_*nus 5 loops r

我需要计算一下

在此处输入图片说明

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

在R中最有效的计算方法是什么?

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

Vit*_*yan 3

一种快速的方法如下:

假设我们有这个向量:

x = c(0,1,2)
Run Code Online (Sandbox Code Playgroud)

ie n=3,并假设 f 是乘法函数:

现在,我们使用expand.grid.unique 自定义函数在向量内产生独特的组合;换句话说,它与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))
}
Run Code Online (Sandbox Code Playgroud)

在我们的向量情况下,当我们 cal 时expand.grid.unique(x,x),它会产生以下结果:

> expand.grid.unique(x,x)
     [,1] [,2]
[1,]    0    1
[2,]    0    2
[3,]    1    2
Run Code Online (Sandbox Code Playgroud)

让我们分配two_by_two给它:

two_by_two <- expand.grid.unique(x,x)
Run Code Online (Sandbox Code Playgroud)

由于假设我们的函数是乘法,因此我们需要计算和积,即的第一列和第二列的点积two_by_two。为此我们需要%*%运算符:

output <- two_by_two[,1] %*% two_by_two[,2]
> output
     [,1]
[1,]    2
Run Code Online (Sandbox Code Playgroud)