更新时间:2022-01-03 00:05:45
另一种尝试:
apply(m[,-ncol(m)] >= m[,ncol(m)], 1, match, x=TRUE)
#[1] NA NA 1 2
或删除apply
:
chk <- m[,-ncol(m)] >= m[,ncol(m)]
replace(max.col(chk,"first"), rowSums(chk)==0, NA)
#[1] NA NA 1 2
它实际上创建了除最后一个列之外的所有m
列的逻辑矩阵,测试值是否为最后一个列值的>=
.然后,使用match
提取每行中第一个TRUE
的位置.
It essentially creates a logical matrix of the all the m
columns except the last, testing if the values are >=
to the last column values. Then the position of the first TRUE
in each row is extracted using match
.
针对Ben的解决方案使用更大的矩阵进行测试的速度:
Testing speed using a bigger matrix against Ben's solution:
m<-matrix(sample(10,1.6e6,replace=TRUE),nrow=4e5)
replicate(5,
system.time(
apply(m[,-ncol(m)] >= m[,ncol(m)], 1, match, x=TRUE)
))
#elapsed 0.7 0.77 0.77 0.76 0.93
replicate(5,
system.time({
m2 <- sweep(m,1,m[,ncol(m)],">=")
v <- apply(m2,1,function(x) which(x)[1])
ifelse(v==ncol(m),NA,v)
}))
#elapsed 1.11 1.04 1.10 1.06 1.06