一种快速的方法如下:
假设我们有这个向量:
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)
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |