哪一行没有申请

时间:2022-04-27 21:24:01

I was sure something of the sort would exist (along the lines of rowSums, etc), but I couldn't find anything. Basically, do this:

我确信会存在某种类型(沿着rowSums等),但我找不到任何东西。基本上,这样做:

apply(mx, 1, which.min)

without using apply so that we can avoid the overhead of calling which.min nrow(mx) times, which could be a large number.

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

1 个解决方案

#1


5  

Thanks to @user20650 for the answer:

感谢@ user20650的答案:

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

With apply:

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

with 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

Old answer: This is the best I came up with. Hopefully somebody has something better like a built in row.which.min or some such. Data:

老答案:这是我想出的最好的答案。希望有人有更好的东西像内置row.which.min或其他一些。数据:

Using pmin, ==, %%, and some vector recycling:

使用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

Not to mention this kind of falls flat on its face if there is more than one minimum value in a row.

如果连续存在多个最小值,更不用说这种下降是平坦的。

#1


5  

Thanks to @user20650 for the answer:

感谢@ user20650的答案:

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

With apply:

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

with 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

Old answer: This is the best I came up with. Hopefully somebody has something better like a built in row.which.min or some such. Data:

老答案:这是我想出的最好的答案。希望有人有更好的东西像内置row.which.min或其他一些。数据:

Using pmin, ==, %%, and some vector recycling:

使用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

Not to mention this kind of falls flat on its face if there is more than one minimum value in a row.

如果连续存在多个最小值,更不用说这种下降是平坦的。