'Sum all elements in a vector except the ith element without for-loop
As the title says. I have a vector and I want to sum all elements in the vector, except the ith element. I can achieve this with a for-loop e.g.
# vector to iterate over
v1 <- 1:5
# somewhere to store results
v2 <- c()
for (i in seq_along(v1)) {
v2[i] <- sum(v1[-i])
}
# desired output
v2
[1] 14 13 12 11 10
I am looking for performance gains, Is it possible to achieve v2 without a for-loop via vectorisation?
Solution 1:[1]
This can be done without a loop using:
sum(v1) - v1
This will, for all elements of v1, provide the sum of all of v1 excluding that element. Since it's a vectorized approach, it will be faster than a loop. https://www.noamross.net/archives/2014-04-16-vectorization-in-r-why/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jon Spring |
