R 生成矩阵/使用外部

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

我是一个新的(~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 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
或者使用
矢量化
d
max

f1 <- function(x,y) max(x,y)
c(outer(1:6, outer(1:6, 1:6, Vectorize(f1)), Vectorize(f1)))

f1
outer()
有三个参数。您的外部
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)))