r - 查找给定列中最常包含最大值的行

标签 r matrix

对可能不太理想的标题表示歉意 - 我似乎想不出更好的标题。

假设我有一个 3x5 矩阵,如下所示:

test.df <- matrix(rep(1:5, 3), nrow = 3)
test.df
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    4    2    5    3
[2,]    2    5    3    1    4
[3,]    3    1    4    2    5

我想返回每列中最常具有最大值的行的索引。我可以结合 which.maxapplytable 来实现,如下所示:

which.max(
    table(
        apply(test.df, 2, which.max)
        )
    )

首先,我将 which.max 应用于每一列:

apply(test.df, 2, which.max)
[1] 3 2 3 1 3

然后,我将 table 应用于生成的向量,并计算给定行被发现具有最大值的次数。

table(
    apply(test.df, 2, which.max)
)
1 2 3 
1 1 3 

最后,我再次使用 which.max 来获取出现次数最多的行的索引。

不幸的是,我需要对大约 20000 个矩阵执行上述操作,其中一些矩阵可能包含数千行。所以我想知道是否有一个更快和/或更优雅的解决方案。最好利用 R 中矩阵运算的力量。

非常感谢!

最佳答案

这个使用rowSums的解决方案似乎提供了相当好的加速:

test.df <- matrix(rep(1:5, 3), nrow = 3)

original = function(m) {
    which.max(
        table(
            apply(m, 2, which.max)
        )
    )
}

row_sums = function(m) {
    which.max(rowSums(apply(m, 2, function(x) {x == max(x)})))
}

library(microbenchmark)

microbenchmark(original(test.df), row_sums(test.df))

计时结果:

Unit: microseconds
              expr    min      lq      mean median     uq      max neval
 original(test.df) 86.725 91.6320 107.19399 92.513 94.462 1376.445   100
 row_sums(test.df) 26.698 28.0895  54.30694 29.741 32.443 2378.536   100

关于r - 查找给定列中最常包含最大值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44542774/

相关文章:

r - 如何用ggplot对齐两个图?

3d 到 2d 投影矩阵

arrays - 计算矩阵每一行中的非零元素

c++ - 复制构造函数错误 : the object has type qualifiers that are not compatible with the member function

python - Python 中二维矩阵的单元分配,没有 numpy

java - 在java中构建项目-项目矩阵

r - 在R中查找多维数组中的维索引

r - 捕获由pbsapply产生的错误

R data.table,访问赋值函数内的矩阵

r - R图,x轴和y轴接触