我有两个向量 r
和 s
。我想找到这两个数组的外部差异,而不是像下面这样的负数
r = rnorm(100000)
s = c(0.02, 0.04, 0.3, 0.43, 0.5, 0.7, 0.8, 0.9)
res = t(pmax(outer(r, s, "-"), 0))
system.time({
res = t(pmax(outer(r, s, "-"), 0))
})
## system elapsed
## 0.05 0.00 0.05
要么
system.time({
x = pmax(r - rep(s, each = length(r)), 0)
res = matrix(x, nrow = length(s), byrow = TRUE)
})
## system elapsed
## 0.05 0.00 0.05
我怎样才能更快地得到 R 中的结果 x?
最佳答案
遵循@thelatemail 的评论:
fun1 <- function(r,s) t(pmax(outer(r, s, "-"), 0))
fun2 <- function(r,s) {
x = pmax(r - rep(s, each = length(r)), 0)
matrix(x, nrow = length(s), byrow = TRUE)
}
fun3 <- function(r,s) {
dr <- length(r)
ds <- length(s)
R <- rep(s, rep.int(length(r), length(s)))
S <- rep(r, times = ceiling(length(s)/length(r)))
res <- pmax(S - R, 0)
dim(res) <- c(dr, ds)
t(res)
}
library(microbenchmark)
microbenchmark(res1 <- fun1(r,s),
res2 <- fun2(r,s),
res3 <- fun3(r,s),
times=20)
# Unit: milliseconds
# expr min lq median uq max neval
# res1 <- fun1(r, s) 43.28387 46.68182 66.03417 78.78109 83.75569 20
# res2 <- fun2(r, s) 50.52941 54.36576 56.77067 60.87218 91.14043 20
# res3 <- fun3(r, s) 34.18374 35.37835 37.97405 40.10642 70.78626 20
identical(res1, res3)
#[1] TRUE
关于r - 在 R 中创建此矩阵的最快方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18478646/