ero1988 - 1 year ago 66

R Question

I would like to ask how I can compute the sum of a vector in R without using one of the the ready functions (sum, mean etc). Sorry for the silly question!!!

I tried the following but it did not work. Could you tell me what I am doing wrong?

The code is:

`x<-c(1,2,3)`

sumfun<-function(y){

sum<-0

for(i in 1:(length(y)-1)){

sum=sum+y[i]

}

print(sum)

}

sumfun(x)

Answer Source

These each return the sum of the elements in x:

```
Sum <- 0
for(x_ in x) Sum <- Sum + x_
Sum
Sum <- 0
for(i in seq_along(x)) Sum <- Sum + x[i]
Sum
Reduce(`+`, x)
# recursive solution
summer <- function(x) if (length(x) > 0) x[1] + Recall(x[-1]) else 0
summer(x)
sum(x)
# limited as it assumes x has three elements
x[1] + x[2] + x[3]
```