Hemanshu Saraf
Hemanshu Saraf

Reputation: 31

Sum of even number using given range in R

I am trying to get sum of even numbers in R Using this code:

x<- c(80:100)
for(i in x) {
  if(i%%2==0) b<-append(b,i)
}
sum(b)

But I am not getting perfect answer. When I print b after the if statement I get b as:

[1] 100 80 82 84 86 88 90 92 94 96 98 100

why the first index is coming 100.

Upvotes: 0

Views: 4015

Answers (1)

lop
lop

Reputation: 91

Before the beginning of your loop, b probably already has a value of 100. Make sure to initiate an empty b at the beginning.

x = c(80:100)
b = c()
for(i in x) {
    if(i %% 2 == 0){
        b = append(b, i)
    }
}
sum(b)

But you could just have done

sum(x[x %% 2 == 0])

Upvotes: 2

Related Questions