我有一堆矢量需要向另一个矢量和.我正在寻找更优雅的矢量添加解决方案,而不是使用'+'运算符.有没有人知道以更舒适的方式做这件事的任何伎俩.谢谢
向量:
a <- c(1,1,0,2,1,0,1,0,1)
b <- c(0,0,1,0,1,1,0,1,0)
c <- c(0,1,1,0,0,2,1,1,1)
Run Code Online (Sandbox Code Playgroud)
我知道做这个的虚拟方式,我期待这样做的优雅
期望的输出:
out <- c(1,2,2,2,2,3,2,2,2)
Run Code Online (Sandbox Code Playgroud)
有效地进行这种操作的任何优雅方式?
我们可以使用rbind将所有向量放在一起,然后使用colSums:
colSums(rbind(a, b, c))
# [1] 1 2 2 2 2 3 2 2 2
Run Code Online (Sandbox Code Playgroud)
标杆:
# bigger input
set.seed(1)
n <- 10^7
a <- runif(n)
b <- runif(n)
c <- runif(n)
d <- runif(n)
e <- runif(n)
f <- runif(n)
# benchmark
microbenchmark::microbenchmark(
colSums = colSums(rbind(a, b, c, d, e, f)),
rowSums = rowSums(cbind(a, b, c, d, e, f)),
Reduce = base::Reduce("+", list(a, b, c, d, e, f)),
S4vReduce = S4Vectors::Reduce('+', lapply(list(a, b, c, d, e, f), lengths)),
JustAdd = a + b + c + d + e + f
)
# Unit: milliseconds
# expr min lq mean median uq max neval cld
# colSums 408.31052 427.94015 470.27181 461.18763 494.1420 651.3383 100 e
# rowSums 349.93752 359.15854 408.82652 397.99315 434.1662 569.3575 100 d
# Reduce 129.43443 134.55584 183.34432 179.88746 208.0281 339.9345 100 b
# S4vReduce 162.90015 166.19150 206.16387 192.73739 212.2146 380.2038 100 c
# JustAdd 73.38243 74.00267 92.68309 76.12524 82.7517 282.6101 100 a
Run Code Online (Sandbox Code Playgroud)