生成矩阵/使用外部

Aky*_*Aky 5 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 maximum of each outcome
apply(mat, 1, max)
Run Code Online (Sandbox Code Playgroud)

用R做一个更好,更简洁的方法吗?我会喜欢用outer这种方式:

outer(1:6, outer(1:6, 1:6, max), max)
Run Code Online (Sandbox Code Playgroud)

但它失败了,错误

外部错误(1:6,1:6,max):dims [product 36]与object [1]的长度不匹配

akr*_*run 6

我们可以使用expand.grid在创建组合data.frame,转化成matrix由获得每一行的最大值rowMaxslibrary(matrixStats).

library(matrixStats)
rowMaxs(as.matrix(expand.grid(rep(list(1:6),3))))
#[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
Run Code Online (Sandbox Code Playgroud)

或者,我们可以使用pmaxexpand.grid

do.call(pmax, expand.grid(rep(list(1:6),3)))
Run Code Online (Sandbox Code Playgroud)

或@Ben Bolker的建议,我们还可以用applyMARGIN=1

apply(expand.grid(rep(list(1:6),3)),1,max) 
Run Code Online (Sandbox Code Playgroud)

另一种选择是outer使用pmax.

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
Run Code Online (Sandbox Code Playgroud)

或者outerVectorizedmax

f1 <- function(x,y) max(x,y)
c(outer(1:6, outer(1:6, 1:6, Vectorize(f1)), Vectorize(f1)))
Run Code Online (Sandbox Code Playgroud)

  • +1,但我可能会使用`apply(expand.grid(rep(list(1:6),3)),1,max)`以一点点速度为代价来坚持基础R /避免依赖在`matrixStats`包... (2认同)