使用@BrodieG 的示例数据,您可以只使用该crossprod
函数:
set.seed(1)
vec1 <- sample(1:10)
vec2 <- sample(1:10)
vec3 <- sample(1:10)
crossprod(cbind(vec1, vec2, vec3))
# vec1 vec2 vec3
# vec1 385 298 284
# vec2 298 385 296
# vec3 284 296 385
出于好奇,一些基准测试:
要运行的功能:
fun1 <- function() {
A <- crossprod(do.call(cbind, lst))
A[upper.tri(A)]
}
fun2 <- function() {
A <- do.call(rbind, lst) %*% do.call(cbind, lst)
A[upper.tri(A)]
}
fun3 <- function() {
combn(
seq_along(lst), 2,
FUN=function(idx) c(lst[[idx[[1]]]] %*% lst[[idx[[2]]]])
)
}
“少量大向量”的基准测试。
library(microbenchmark)
set.seed(1)
n <- 5
lst <- setNames(replicate(n, sample(1:100000), simplify = FALSE),
paste0("V", sequence(n)))
microbenchmark(fun1(), fun2(), fun3())
# Unit: milliseconds
# expr min lq median uq max neval
# fun1() 6.909651 6.992031 8.432346 8.520301 74.12263 100
# fun2() 17.290101 18.811134 19.144601 21.292544 88.10602 100
# fun3() 22.841209 24.283113 24.427876 25.820158 91.14007 100
没有足够的耐心对中等数量的中等向量进行基准测试:
set.seed(1)
n <- 1000
lst <- setNames(replicate(n, sample(1:1000), simplify = FALSE),
paste0("V", sequence(n)))
system.time(fun1())
# user system elapsed
# 0.245 0.004 0.251
system.time(fun2())
# user system elapsed
# 0.407 0.016 0.425
system.time(fun3())
# user system elapsed
# 14.216 0.004 14.339