lundi 20 janvier 2020

How to reference other columns in an ifelse using dplyr mutate

Dataset example is below. When temp.change == 0, I would like to have R just copy the status of the cell above in column X into a new column. I have created another column, shifting the data in column X down to reference it. In otherwords, if temp.change == 0, then make X = X_shifted. I realize that if there are multiple 0's in a row, this also might be an issue with this method. The binary X column is the result of many ifelse statements about column temp.change

temp.change     X   X_shifted
9.5             1     NA
1               1     1
-0.5            1     1
-1              0     1
-0.5            0     0
0               1     0
0               1     1
3               1     1          
0               0     1          
1               1     0

Is there a way to reference another column in an ifelse statement? I would prefer to try to find a way to do so using dplyr, since I have a very large dataset and it is rather quick. I have tried the code below, and a few non dplyr methods without any success.

  mutate(X_fixed = ifelse(temp.change_prev==0, X_shifted, X))

Expected result:

temp.change     X   X_shifted  X_fixed
9.5             1     NA         1
1               1     1          1
-0.5            1     1          1
-1              0     1          0
-0.5            0     0          0
0               1     0          0
0               1     1          0
3               1     1          1
0               0     1          1
1               1     0          1  

Aucun commentaire:

Enregistrer un commentaire