R 生成矩阵/使用外部
我是一个新的(~1天大)R用户。我正试图通过一个六面骰子的三次投掷来产生所有216个结果。关键是对每个三元组应用一些函数(比如,最大面值)。这就是我想到的:R 生成矩阵/使用外部,r,R,我是一个新的(~1天大)R用户。我正试图通过一个六面骰子的三次投掷来产生所有216个结果。关键是对每个三元组应用一些函数(比如,最大面值)。这就是我想到的: mat <- matrix(numeric(0), ncol=3) for (i in 1:6) { for (j in 1:6) { for (k in 1:6) { mat <- rbind(mat, c(i, j, k)) } } } # find
mat <- matrix(numeric(0), ncol=3)
for (i in 1:6) {
for (j in 1:6) {
for (k in 1:6) {
mat <- rbind(mat, c(i, j, k))
}
}
}
# find maximum of each outcome
apply(mat, 1, max)
但它失败了,出现了错误
外部错误(1:6,1:6,最大值):
dims[product 36]与对象[1]的长度不匹配
我们可以使用
expand.grid
在data.frame
中创建组合,转换为matrix
,并通过rowMaxs
从库(matrixStats)
获得每行的最大值
或者我们可以使用pmax
和expand.grid
do.call(pmax, expand.grid(rep(list(1:6),3)))
或者按照@Ben Bolker的建议,我们也可以使用apply
和MARGIN=1
apply(expand.grid(rep(list(1:6),3)),1,max)
另一个选项是使用
pmax
的outer
c(outer(1:6, outer(1:6, 1:6, FUN=pmax), FUN= pmax))
#[1] 1 2 3 4 5 6 2 2 3 4 5 6 3 3 3 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 2
#[38] 2 3 4 5 6 2 2 3 4 5 6 3 3 3 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 3 3
#[75] 3 4 5 6 3 3 3 4 5 6 3 3 3 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 4 4 4
#[112] 4 5 6 4 4 4 4 5 6 4 4 4 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 5 5 5 5
#[149] 5 6 5 5 5 5 5 6 5 5 5 5 5 6 5 5 5 5 5 6 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6
#[186] 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
或者使用矢量化dmax
f1 <- function(x,y) max(x,y)
c(outer(1:6, outer(1:6, 1:6, Vectorize(f1)), Vectorize(f1)))
f1outer()
有三个参数。您的外部outer()
只有两个。对于函数参数不要转换为字符,max
不是“max”
。(有些函数,有一个函数参数,也可以包含一个字符串,但不是全部)@jogo,很抱歉,遗漏的1:6是一个输入错误。但它仍然不起作用:outer(outer(最大1:6,1:6),最大1:6)
抛出相同的值error@Aky您是否测试了下面发布的解决方案?请参阅:请更正您在问题中的参数输入错误。谢谢。。你能解释一下为什么max
失败吗?好的,我以前没有遇到过矢量化。稍后我将研究它。+1,但我可能会使用apply(expand.grid(rep(list(1:6),3)),1,max)
,但代价是要以一点速度来坚持基本R/避免依赖矩阵状态
包。。。
c(outer(1:6, outer(1:6, 1:6, FUN=pmax), FUN= pmax))
#[1] 1 2 3 4 5 6 2 2 3 4 5 6 3 3 3 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 2
#[38] 2 3 4 5 6 2 2 3 4 5 6 3 3 3 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 3 3
#[75] 3 4 5 6 3 3 3 4 5 6 3 3 3 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 4 4 4
#[112] 4 5 6 4 4 4 4 5 6 4 4 4 4 5 6 4 4 4 4 5 6 5 5 5 5 5 6 6 6 6 6 6 6 5 5 5 5
#[149] 5 6 5 5 5 5 5 6 5 5 5 5 5 6 5 5 5 5 5 6 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6
#[186] 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
f1 <- function(x,y) max(x,y)
c(outer(1:6, outer(1:6, 1:6, Vectorize(f1)), Vectorize(f1)))