ero1988
ero1988

Reputation: 13

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)

Upvotes: 0

Views: 9559

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269431

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]

Upvotes: 1

Mestica
Mestica

Reputation: 1529

You should change the range of your for loop to make it read the values of the first up until the last index, thus remove the -1 in for(i in 1:(length(y)-1)). The fix makes the entire code look like:

x<-c(1,2,3)

sumfun<-function(y){
  sum<-0
  for(i in 1:(length(y))){
    sum=sum+y[i]
  }
  print(sum)
}
sumfun(x)

This should print out 6.

Upvotes: 0

Related Questions