【问题标题】:which.min by row without applywhich.min 按行不应用
【发布时间】:2015-03-07 01:00:49
【问题描述】:

我确信会存在类似的东西(如rowSums 等),但我找不到任何东西。基本上,这样做:

apply(mx, 1, which.min)

不使用apply 这样我们就可以避免调用which.min nrow(mx) 次数的开销,这可能是一个很大的数字。

【问题讨论】:

  • @user20650,太棒了,不敢相信我在which.min 的文档中错过了它;请作为答案发布,我会接受。
  • 请随时更新您的 - 您已经完成了所有艰苦的工作
  • @user20650,我什至不能再接受我自己的答案两天,所以请发布您的答案,以便您获得应得的代表!

标签: r apply min


【解决方案1】:

感谢@user20650 的回答:

set.seed(1)
mx <- matrix(runif(1e7), ncol=5)

apply:

system.time(which.min.mx <- apply(mx, 1, which.min))
# user  system elapsed 
#  4.7     0.0     4.7 

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

旧答案:这是我想出的最好的答案。希望有人有更好的东西,比如内置的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

如果连续有多个最小值,更不用说这种摔倒了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 2017-08-28
    • 2020-04-17
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多