Home > Enterprise >  Turning to variables into one based on logical criteria
Turning to variables into one based on logical criteria

Time:12-22

I have this dataframe that consists of three variables: id, wwb and ub_bene

       id   wwb ub_bene    
    <dbl> <dbl>   <dbl>
 1 800009     0       0
 2 800009     0       1
 3 800009     1       0
 4 800009     1       0
 5 800009     0       0
 6 800015     0       0
 7 800015     0       1
 8 800015     0       0
 9 800015     1       0
10 800015     0       1
11 800033    NA      NA
12 800033    NA      NA
13 800042     0       0
14 800042     0       1
15 800042    NA      NA    

However. Im looking for some way to turn these variables into one, so that:

If wwb = 1, then column C will be 2, and if ub_bene = 1, then column C will be 1 and otherwise 0.

This is what I want to obtain:

       id   wwb ub_bene  c
    <dbl> <dbl>   <dbl> <dbl> 
 1 800009     0       0   0
 2 800009     0       1   1
 3 800009     1       0   2
 4 800009     1       0   2
 5 800009     0       0   0  
 6 800015     0       0   0
 7 800015     0       1   1
 8 800015     0       0   0
 9 800015     1       0   2
10 800015     0       1   1
11 800033    NA      NA   NA
12 800033    NA      NA   NA
13 800042     0       0   0
14 800042     0       1   1
15 800042    NA      NA   NA

Any easy solution to obtain this?

Thanks in advance!

CodePudding user response:

You can apply just a simple math on the columns like,

df$c <- df[,2] *2   df[,3]

CodePudding user response:

Try a nested ifelse:

df$c <- ifelse(df$wwb == 1, 2, ifelse(df$ub_bene == 1, 1, 0))
  • Related