【问题标题】:Getting maximum value for specific matrix element over multiple matrices在多个矩阵上获取特定矩阵元素的最大值
【发布时间】:2015-06-21 20:36:31
【问题描述】:

我有很多矩阵(20 行/20 列)。我想在所有这些矩阵中找到特定元素(单元格)的最大值,例如第 9 行第 17 列。

这已经接近了: R: Getting maximum value from all matrices in a list 但我无法根据我的需要重写它。现在我的矩阵在一个列表中。

有什么想法吗?

【问题讨论】:

  • 如果不是链接中的示例,您可能需要根据该示例显示一些示例和预期结果

标签: r list matrix max element


【解决方案1】:
library(plyr)

mats <- llply(1:1000, function(x) replicate(20, rnorm(20)))

getEntry <- function(mat, row, col) {

  mat[row, col]

}

getMax <- function(mats, row, col) {

  max(laply(mats, function(x) getEntry(x, row, col)))

}

# Get max of row 2, col 3 & row 12, col 19
getMax(mats, 2, 3)
getMax(mats, 12, 19)

这应该可以满足您的要求。它从每个矩阵中提取指定的单元格,然后取所有选项的最大值。

【讨论】:

  • llply/laply 来自plyr。您需要提及library(plyr)。此外,这可以通过 base R 函数 sapply/lapply 等来完成。我发布了一个答案,但不知道答案已经发布。
【解决方案2】:

这是一个基本解决方案(使用 akrun 已删除答案中的示例数据),但实际上不需要匿名函数:

 set.seed(24)
 lst <- lapply(1:4, function(i) matrix(sample(0:9, 20*20,
         replace=TRUE), ncol=20))
 str(lst)

List of 4
 $ : int [1:20, 1:20] 2 2 7 5 6 9 2 7 8 2 ...
 $ : int [1:20, 1:20] 4 1 1 8 9 5 7 0 1 6 ...
 $ : int [1:20, 1:20] 1 8 3 1 2 6 2 3 7 5 ...
 $ : int [1:20, 1:20] 2 3 5 4 3 2 7 2 1 5 ...


 max( sapply(lst, "[", i=9, j=7) )  # Use `[` as a function with 3 parameters:
                                      #  object and 2 indices
[1] 8

【讨论】:

  • 这也有效。我考虑过不使用匿名函数,但为了便于阅读,我决定将其包含在内。
  • 类似:library(abind); arr &lt;- do.call(abind,c(lst,list(along=3))); max(arr[i,j,]) 无论如何,使用数组而不是列表可能会很方便。
【解决方案3】:
do.call(pmax,lst)[i,j]

这行得通,除非我误解了这个问题。以这种方式为所有元素取最大值可能会很浪费,但我怀疑这有什么大不了的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    相关资源
    最近更新 更多