【问题标题】:generating matrices/using outer生成矩阵/使用外部
【发布时间】:2016-02-15 23:31:34
【问题描述】:

我是新的(约 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)

有没有更好更简洁的方法来使用 R 来做到这一点? 我本来希望这样使用outer

outer(1:6, outer(1:6, 1:6, max), max)

但它失败并出现错误

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

【问题讨论】:

  • outer() 具有三个参数/参数。你外面的outer() 只有两个。对于函数参数,不要强制转换为字符,max 不是"max"。 (某些具有函数参数的函数也可以容忍字符串,但不是全部)
  • @jogo,抱歉,丢失的 1:6 是一个错字。但它仍然不起作用:outer(outer(1:6, 1:6, max), 1:6, max) 抛出相同的错误
  • @Aky 你测试过下面发布的解决方案吗?
  • 请更正您对问题中参数的错字。

标签: r


【解决方案1】:

我们可以使用expand.griddata.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

或者我们可以使用pmaxexpand.grid

do.call(pmax, expand.grid(rep(list(1:6),3)))

或者按照@Ben Bolker 的建议,我们也可以使用applyMARGIN=1

apply(expand.grid(rep(list(1:6),3)),1,max) 

另一个选项是outerpmax

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

或者outerVectorized max

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

【讨论】:

  • 谢谢.. 你能解释一下为什么max 失败了吗?
  • 好的,我之前没有遇到过 Vectorize。我稍后会研究它。
  • +1,但我可能会使用 apply(expand.grid(rep(list(1:6),3)),1,max) 以牺牲一点速度来坚持使用基本 R/避免依赖 matrixStats 包 ...
猜你喜欢
  • 2022-12-11
  • 2021-04-15
  • 2019-02-27
  • 2020-03-20
  • 1970-01-01
  • 1970-01-01
  • 2015-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多