ero1988 ero1988 - 4 months ago 8
R Question

How to compute the sum of a vector in r using a for loop

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

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]