我有一个像这样的矩阵
library(matrixStats) ## for `rowMaxs`
mymat <- matrix(c(1:10,1:10), 5,4)
# [,1] [,2] [,3] [,4]
#[1,] 1 6 1 6
#[2,] 2 7 2 7
#[3,] 3 8 3 8
#[4,] 4 9 4 9
#[5,] 5 10 5 10
myvector <- rowMaxs(mymat)
我希望每行中的所有元素都替换为0,期望该行中的最大/最大值。在此示例中,每行有两个最大值,因此预期结果为:
# [,1] [,2] [,3] [,4]
#[1,] 0 6 0 6
#[2,] 0 7 0 7
#[3,] 0 8 0 8
#[4,] 0 9 0 9
#[5,] 0 10 0 10
答案 0 :(得分:2)
## replace all elements to 0 except for row maximum; multiple maximum allowed
## recycling rule is used here, so `myvector` is replicated to be a full matrix
## i.e., equivalently: mymat[ mymat < rep.int(myvector, ncol(mymat)) ] <- 0
mymat[mymat < myvector] <- 0
如果要反向操作,即将行最大值(最大值)设置为0,请使用
mymat[mymat == myvector] <- 0
您已获得myvector
matrixStats::rowMaxs
。对于想要使用R base的其他人来说,max.col
很优雅:
## matrix indexing is used, i.e., we index matrix with a two-column matrix
myvector <- mymat[ cbind( 1:dim(mymat)[1], max.col(mymat) ) ]
答案 1 :(得分:1)
我认为我的第一个解决方案将与哲源的帖子一致,但方式略有不同:
mymat[mymat != matrix(rep(rowMaxs(mymat), ncol(mymat)),ncol=ncol(mymat))] <- 0
或申请:
t(apply(mymat, 1, function(x) {x[x != max(x)] <- 0; x}))
两个输出
[,1] [,2] [,3] [,4]
[1,] 0 6 0 6
[2,] 0 7 0 7
[3,] 0 8 0 8
[4,] 0 9 0 9
[5,] 0 10 0 10