感谢@ user20650的答案:
set.seed(1)
mx <- matrix(runif(1e7), ncol=5)
Run Code Online (Sandbox Code Playgroud)
用apply:
system.time(which.min.mx <- apply(mx, 1, which.min))
# user system elapsed
# 4.7 0.0 4.7
Run Code Online (Sandbox Code Playgroud)
用max.col:
system.time(mx.mins.2 <- max.col(-mx, ties="first"))
# user system elapsed
# 0.12 0.00 0.13
all.equal(which.min.mx, mx.mins.2)
# [1] TRUE
Run Code Online (Sandbox Code Playgroud)
老答案:这是我想出的最好的答案.希望有人有更好的东西像内置row.which.min或其他一些.数据:
使用pmin,==,%%,和一些载体回收:
system.time({
row.min <- do.call(pmin, as.data.frame(mx))
mx.mins <- which(t(mx == row.min)) %% ncol(mx)
mx.mins[!mx.mins] <- ncol(mx)
})
# user system elapsed
# 0.51 0.00 0.51
all.equal(which.min.mx, mx.mins)
# [1] TRUE
Run Code Online (Sandbox Code Playgroud)
如果连续存在多个最小值,更不用说这种表面凹陷了.