jeudi 6 juin 2019

Why in ifelse function with AND statements the wrong results

I have the following dataset: ''' df1 <- data.frame(number = c(1,1,0,0,0,0,0,1,1)) '''

In this dataset i want to create a second column, which shows if in the certain row of the first column there is a case, when first and second lags are equal to 0 and the first lead equals to 1. If this is a case, so the number 1 is put in the second column where change from 0 to 1 occurred (if not the case so equals to 44. As a result, in this output all rows in the second column should equal to 44 except the 8th.

here is my code. and in the comments below I will put a photo of the required result.

df1$t<-ifelse(df1[,1]==1 & lag(df1[,1]==0,1,default = 44) & lag(df1[,1]==0,2,default = 44)
                              & lead(df1[,1]==1,1,default = 44)
                              ,1,44)

Aucun commentaire:

Enregistrer un commentaire