mardi 23 juin 2020

Creating a new variable and altering dependent variables in r using ifelse

Let's say we have a df as follows:

A  B  C  D  E
1  1  0  0  1
0  0  1  0  0
0  0  0  0  1
1  1  1  1  0
0  1  1  0  1
1  0  1  0  0   

So I would like to make another variable F which says, if the sum of A:D is greater than 1, F is 1 and A:D are 0.

Additionally, If E = 0, then F = 0.

So here's how I wrote it but it's not working...

#Counter
df<- df %>% 
       mutate(case_count = A+B+C+D)

df$F <- ifelse(df$E == 1, 0,
              ifelse(df$case_count > 1, 
                     df$A == 0 & 
                     df$B  == 0 &
                     df$C  == 0 &
                     df$D  == 0 &
                     df$F  == 1,0))

And the correct result here should then be

A  B  C  D  E  case_count F 
1  1  0  0  1           2 0
0  0  1  0  0           1 0
0  0  0  0  1           0 0
0  0  0  0  0           4 1
0  1  1  0  1           2 0
0  0  0  0  0           2 1

Aucun commentaire:

Enregistrer un commentaire