Problems with control statement if...else in R -
i beginner in r , here's code:
for (i in 1:7){ testing<-vector(length=(length(yy)-3)) if(all(yy[i:(i+2)]==0)) testing[i]<-1 else testing[i]<-na } yy refers following vector of length 10:
> yy [1] 1 0 0 0 0 1 0 1 0 1 testing predict function output, predict 1 if previous 3 elements in yy 0.if not, not predict anything, , na. since yy has total of 10 elements, testing have total of 7 elements (therefore length 7) however, instead of giving me output of 1s , nas, giving this:
> testing [1] false false false false false false na i cannot figure out why, great. thank you.
you should define testing outside loop:
testing<-vector(length=(length(yy)-3)) (i in 1:7){ if(all(yy[i:(i+2)]==0)) testing[i]<-1 else testing[i]<-na } testing [1] na 1 1 na na na na for task couls use rollapply zoo:
library(zoo) rollapply(yy, 3, function(x) ifelse(all(x == 0), 1, na)) [1] na 1 1 na na na na na
Comments
Post a Comment