假设有以下矩阵,我想要找到第二列中的最大值:
mat <- matrix(c(1:3,7:9,4:6), byrow = T, nc = 3)
mat
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 7 8 9
[3,] 4 5 6
我知道max(mat[,2])
会返回8。如何返回行索引,例如这种情况下的第二行?
查看?which.max
> which.max( matrix[,2] )
[1] 2
请查看?order
。您只需要最后一个索引(或第一个索引,按降序排列),所以以下代码可以解决问题:
order(matrix[,2],decreasing=T)[1]
row(y)[y==max(y)]
如果您想提取行:
y[row(y)[y==max(y)],] # this returns unsorted rows.
要返回排序后的行,请使用:
y[sort(row(y)[y==max(y)]),]
col(y)
和悬挂逗号的位置,您还可以提取列。y[,col(y)[y==max(y)]]
要仅查找特定列中的最大行,例如第2列,您可以使用以下方法:
seq(along=y[,2])[y[,2]==max(y[,2])]
条件语句可以根据不同的需求进行灵活设置。
请参考Phil Spector所著的《S和S-Plus简介》第五章,获取更多想法。
mat <- matrix(c(1:3,7:9,4:6), byrow = T, nc = 3)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 7 8 9
[3,] 4 5 6
mat %>% as_tibble() %>% filter( V2 == max(V2) )
# A tibble: 1 x 3
V1 V2 V3
<int> <int> <int>
1 7 8 9
有一个函数max.col()
。对于每一行,它会找到具有最大值的列:
max.col(mat)
[1] 3 3 3
如果要找到每列的最大行,则只需转置矩阵:
max.col(t(mat))
[1] 2 2 2
rank
和order
之间感到困惑。order
返回每个元素的索引,但按元素值排序。rank
返回每个元素如果首先对列表进行排序,则将具有的索引位置。因此,order
返回当前索引值;可以用作Pandas术语中的“索引器”。 - Nate Anderson