Soulja Boy
Soulja Boy

Reputation: 7

Looking to find the sum in R

I keep getting NA for the code below to find the sum of vector in R without using sum():

total <- 0
for ()) {
    add = gg[n] + gg[n+1]
    total = total + add
}

Upvotes: 1

Views: 69

Answers (1)

Flecflec
Flecflec

Reputation: 243

Your getting a NA because gg[n+1] does not exist when last step (length(gg)) : so it finally adds NA to your sum.

Use for (n in (1:(length(gg)-1)) ) instead

(and tip to debug : print the contents of your variables at each steps using print() - launch code below to see your issue :

 total <- 0
 for (n in (1:length(gg)) ) {
   print(paste("n: ",n))
   print(paste("gg for n : ",gg[n], "and n+1: ",gg[n+1]))

  add = gg[n] + gg[n+1]
  print(paste("add when loop = ", n, ":", add))
  total = total + add
  print(total)
}
total

Upvotes: 2

Related Questions