user1478061 user1478061 - 3 months ago 41
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?

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

or write a shorter loop:

s <- 0
for(a in basket) s<- s+a