lundi 12 février 2018

ifelse with multiple outputs in R

Is it possible to obtain multiple outputs with ifelse? I would like to create a variable ExpectedVariable with either 0s or 1s. If VariableA has a value of 0, then I need ExpectedVariable to be 0 for the current row and for the previous row. If VariableA has a value of 1, then I need ExpectedVariable to be 1.

I was thinking of something like this (which as it is doesn't work):

 mydata$ExpectedVariable <- ifelse(mydata$VariableA == 0, (mydata$ExpectedVariable & lag(mydata$ExpectedVariable) <- 0), 1)

Example:

         VariableA    ExpectedVariable
row1     1            1
row2     1            1
row3     1            1
row4     1            1
row5     1            1
row6     1            0
row7     0            0
row8     1            1
row9     1            0
row10    0            0
row11    1            1
row12    1            1
row13    1            0
row14    0            0

Aucun commentaire:

Enregistrer un commentaire