user1478061 - 3 months ago 41

R Question

I've a vector.

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

If I've to sum, I could call

`sum(basket)`

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

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

or write a shorter loop:

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