I'm trying to use a if statement inside a for loop so that if the if condition isn't met R will stop running the loop for that i value but will continue to run the whole loop, and I think I'm having a (simple?) syntax error that is giving me a different result from what I expected.
Below is my example dataset and my loop:
test <- matrix(ncol=3, nrow=3, data = c(10, 20, 30, NA, 10, 20, 10, 30, 20), byrow = T)
mean_fun<-function(x,y){
mean <- sum(x,y)/2
return(mean)
}
for (i in (1:nrow(test))){
var1 <- vector()
var2 <- vector()
var1[i] <- mean_fun(test[i,1], test[i,2])
if (is.na(var1[i]==TRUE)) next
var2[i] <- mean_fun(var1[i], test[i,3])
print(var2)
}
If I just calculate var1 values in my loop, var1 = c(15, NA, 20). I don't want to calculate var2 if my var1 == NA. In short, the result I wanted to get from this loop is var2 = c(22.5, NA, 20.0).
But when I run this loop, I'm getting [1] 22.5 [1] NA NA 20 which would mean that the loop ran okay for i=1 and maybe i=2 but got messed up during i=2 or i=3? I can't figure out how the syntax worked so that it's giving me NA NA 20. Any advice would be greatly appreciated!
Aucun commentaire:
Enregistrer un commentaire