矩阵中的行最大值

时间:2015-02-24 12:03:02

标签: r matrix max

我有一个10乘3的矩阵(称为u_V),我想知道哪一列我的行最大。我知道如何使用which.max为给定的行执行此操作,并且我这样编码以获取每行的信息:

u <- rbind(which.max(u_V[1, 1:3]), which.max(u_V[2, 1:3]), which.max(u_V[3,  1:3]), 
which.max(u_V[4, 1:3]), + which.max(u_V[5, 1:3]), which.max(u_V[6, 1:3]),
which.max(u_V[7, 1:3]), which.max(u_V[8, 1:3]), + which.max(u_V[9, 1:3]),
which.max(u_V[10, 1:3]))
u

我想知道是否有更有效的方法来获得这些结果,循环或其他东西。因为目前我将行固定为10但它可能会改变,我不想以相同的方式编码50行。为了确保我的问题很明确,我并不十分关心最大值是什么,而是关注哪一列。

2 个答案:

答案 0 :(得分:2)

apply答案的替代方法是使用max.col

set.seed(1)
x <- matrix(nrow=10,ncol=3,data=runif(3*10))
max.col(x)
#  [1] 3 1 2 1 2 1 1 2 3 2
identical(max.col(x), apply(x, 1, which.max))
# [1] TRUE

答案 1 :(得分:1)

我同意尼克考克斯的观点,但看到我打开R并精神上处理了答案,在这里(带有一些示例数据)

> x<-matrix(nrow=10,ncol=3,data=runif(3*10))
> x
             [,1]      [,2]      [,3]
 [1,] 0.861535956 0.2773221 0.7394190
 [2,] 0.763581333 0.5791367 0.2645617
 [3,] 0.339701933 0.6610865 0.8578069
 [4,] 0.783707450 0.7398291 0.2323307
 [5,] 0.005491861 0.1027971 0.3293975
 [6,] 0.491010167 0.2331927 0.9522282
 [7,] 0.445526237 0.2195360 0.5979696
 [8,] 0.372839795 0.9215390 0.2849639
 [9,] 0.276297446 0.8179302 0.4035756
[10,] 0.735914381 0.8797293 0.3853151
> apply(x, 1, which.max)
 [1] 1 1 3 1 3 3 3 2 2 2
>

<强>更新 正如@Ananda所观察到的,实际上有一个本地函数可以做你想要的。因此,它是您想要在实践中使用的。我认为我的答案仍然很好,但是:)

> m<-100000;n<-100;x<-matrix(nrow=m,ncol=n,data=runif(m*n))
> ptm <- proc.time()
> y<-max.col(x)
> proc.time() - ptm
   user  system elapsed 
   0.14    0.06   36.78 
> ptm <- proc.time()
> z<-apply(x, 1, which.max)
> proc.time() - ptm
   user  system elapsed 
   0.51    0.38   20.83 
>