这会更快一些:
wii <- 1/(1/(1-1/(wii == 0)) + wii)
更好的是(而且更简单!)是评论中的@sgibb 版本(对于大多数为 0 的矩阵来说它会更好):
tmp <- which(wii != 0)
wii[tmp] <- 1/wii[tmp];
基准:
N = 1e3
wii = matrix(sample(c(0, 10), N*N, T), nrow = N)
op = function(wii) {
wii <- 1/wii
wii[is.infinite(wii)] <- 0
}
so = function(wii) {
tmp <- wii != 0 # doing this is faster than Señor O's original answer
wii[tmp] <- 1/wii[tmp]
}
ed = function(wii) {
wii <- 1/(1/(1-1/(wii == 0)) + wii)
}
sg = function(wii) {
tmp <- which(wii != 0)
wii[tmp] <- 1/wii[tmp];
}
require(microbenchmark)
microbenchmark(op(wii), so(wii), ed(wii), sg(wii), times = 100)
#Unit: milliseconds
# expr min lq median uq max neval
# op(wii) 47.91634 64.51116 76.39793 88.13995 125.72246 100
# so(wii) 82.00116 114.90850 133.25893 150.97547 196.63302 100
# ed(wii) 26.80661 41.64416 66.26577 79.08794 130.08377 100
# sg(wii) 30.86709 43.68241 50.01369 61.89294 97.65006 100