Home > Net >  Create a formula using multiple conditions on multiple columns
Create a formula using multiple conditions on multiple columns

Time:08-29

I'm trying to create a new column using a formula making use of multiple conditions on multiple columns.

This is an example of what I'm trying to do:

df$new_column <- exp((0.17 if 10 ≤ df$column1 < 20)   (0.56 if 20 ≤ df$column1 <50)   (0.61 if 50 ≤ df$column1 < 88)   
(0.32 if 88 ≤ df$column1 )   (0.12 if df$column2 == "a" )   (0.24 if df$column2 == "b")   (0.34 if df$column2 == "c")   
0.87   (0.22 if df$column3 == "a" )   (0.89 if df$column4 == "a") (0.65*((100 – df$column5)/10))   
(0.23 if df$column6 == "a")   (0.12 if df$column6 == "b")   (0.55 * df$column7))

CodePudding user response:

This solution seems to work:

df$new_column <- exp(if_else(df$column1 >= 10 & df$column1 < 20, 0.17, 0)   if_else(df$column1 >= 20 & df$column1 < 50, 0.56, 0)  
                               if_else(df$column1 >= 50 & df$column1 < 88, 0.61, 0)   if_else(df$column1 >= 88, 0.32, 0)  
                               if_else(df$column2 %in% "a", 0.12, 0)   if_else($df$column2 %in% "b", 0.24, 0)  
                               if_else(df$column2 %in% "c", 0.34, 0)   0.126   if_else(df$column3 %in% "a", 0.22, 0)  
                               if_else(DatiUsati1$df$column4 %in% "a", 0.89, 0)   0.066 * ((170 - df$column5)/10)   
                               if_else(df$column6 %in% "a", 0.23, 0)   
                               if_else(df$column6 %in% "b", 0.12, 0)   0.01 * df$column7))
  • Related