# NA_Real Values in For Loop

Hi everyone, I am trying to read some values into R and then calculate an SST values, but my initial SST loop will not run properly. I keep getting "NA_Real" values. My code is pretty long so I abbreviated it below,

rm(list=ls())

val <- 0
s <- 0

meanval = 0
SST = 0

#read in every value in table
val[1] = data[2,2]
val[2] = data[3,2]
val[3] = data[4,2]
val[4] = data[5,2]
val[5] = data[6,2]
val[6] = data[7,2]
#supposed to be 27 values but I edited them out

#loop to calc all SST's (I have 27 values so my code is looping 1:27)
for(i in 1:6){
SST = SST + ((val[i]-mean(val))^2)
}

After this loop I then calculate all my other SST values that not need to be looping. Since this loop above is getting "NA_real" values, my SST values after the loop are not being calculated.

Could I please have some advice on how to fix my loop?

Do you need to use a loop? Can you provide a reproducible example?

You just need to check for NA values.

``````for(i in 1:6){
if (!is.na(val[i])){
SST <- SST + (val[i]-mean(val, na.rm = TRUE))^2
}
}
``````

By the way, in R you would not usually use a loop for this, it's inefficient. This is better:

``````SST <- sum((val-mean(val, na.rm = TRUE))^2, na.rm = TRUE)
``````

or

``````val <- val[!is.na(val)]
SST <- sum((val-mean(val))^2)``````

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.