如何执行所有可能的算术运算组合?



我正在寻找一些关于如何评估 R 中算术运算排列的帮助。

与这里的这个问题类似。

使用 gtools 包,我可以轻松生成算术运算符的排列

library(gtools)
#permutations of operations
permutations(2, 3, c("*", "/"), repeats.allowed = TRUE)

这给出了以下输出

[,1] [,2] [,3]
[1,] "*"  "*"  "*"
[2,] "*"  "*"  "/" 
[3,] "*"  "/"  "*" 
[4,] "*"  "/"  "/" 
[5,] "/"  "*"  "*"
[6,] "/"  "*"  "/" 
[7,] "/"  "/"  "*" 
[8,] "/"  "/"  "/" 

我的问题是如何采用这些排列并在其他地方使用它们。

我运气好运地使用:

eval(parse(text=paste(x)))

但我认为这是错误的处理方式。

用法示例:

包含整数的示例数据帧:

testmatrix <- as.data.frame(matrix(1:16, ncol = 4)) #dataframe with 4 columns with integers up to 16

数据帧:

V1 V2 V3 V4
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16

根据上面的算术排列创建计算列

第一个排列是"*""*""*"

用 DPLYR 计算:

testmatrix %>% mutate(.[[1]]*.[[2]]*.[[3]]*.[[4]])

所以排列的结果:

... V1 V2 V3 V4 Result of permutation V1*V2*V3*V4 1 5 9 13 585 2 6 10 14 1680 3 7 11 15 3465 4 8 12 16 6144 ...

然后我想对算术运算的所有排列执行此操作,而无需手动键入它。

非常感谢

马 特

m <- matrix(1:16,4,4)

使用 base-R 函数获取ops

ops <- do.call(expand.grid,
c(list(replicate(3,c("*","/"),simplify=FALSE)),
list(stringsAsFactors=FALSE)))

使用get()而不是eval()- 更安全/更有原则。 这有点笨拙,也许可以使用Reduce()获得更好/更通用的解决方案:

f <- function(x,ops) {
r1 <- get(ops[[1]])(x[1],x[2])
r2 <- get(ops[[2]])(r1,x[3])
r3 <- get(ops[[3]])(r2,x[4])
return(r3)
}

对于每组运算符,apply()矩阵的行...

res <- vector("list",nrow(ops))
for (i in seq(nrow(ops))) {
res[[i]] <- apply(m,1,f,ops=ops[i,])
}
res

我没有看到使用Reduce()的方法,但这里有一个稍微通用的f()版本:

f <- function(x,ops) {
r <- get(ops[[1]])(x[1],x[2])
for (j in 2:length(ops)) {
r <- get(ops[[j]])(r,x[j+1])
}
return(r)
}

相关内容

最新更新