user1478061 user1478061 - 1 year ago 113
R Question

Sum without use of loop in R

I've a vector.

basket <- c(4,5,10,102,10);

If I've to sum, I could call


If I've to use for loop to find out sum,

total <- 0; len <- length(basket); for(i in 1:len) {total <- total + basket[i]}

Is there a way I could find total, without using sum(), or using this lengthy for loop construct?

Answer Source
add <- function(x) Reduce("+", x)

or write a shorter loop:

s <- 0
for(a in basket) s<- s+a
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download