Home > OS >  Ifelse with 3 conditions and 2 outcomes
Ifelse with 3 conditions and 2 outcomes

Time:03-18

I want to replace the values of var2 subject to conditions as follows:

  1. if var1 is not equal to 1 or 2, then var2 equals its original value
  2. if var1 equals 1 or 2, and var3 equals 1, then var2 equals its original value. Otherwise var2 equals 1

I have this:

enter image description here

var1 var2 var3
1 .35 1
2 .42 .11
3 .51 .21
4 .39 1
var1 var2 var3
1 .35 1
2 1 .11
3 .51 .21
4 .39 1

This is my code, but it is not producing the desired output.

df <- data.frame(var1=c(1, 2, 3, 4), var2=c(.35, .42, .51, .39),
             var3=c(1, .11, .21, 1))

df2 <- df %>% mutate(var2 = ifelse(var1 != 1 | var1 != 2, var2, 
                          ifelse(var1 == 1 | var1 == 2 & var3 == 1, var2, 1)))

CodePudding user response:

Your code just needed change in & and |

df2 <- df %>% mutate(var2 = ifelse(var1 != 1 & var1 != 2, var2, 
                                   ifelse(var1 == 1 & var1 == 2 | var3 == 1, var2, 1)))

  var1 var2 var3
1    1 0.35 1.00
2    2 1.00 0.11
3    3 0.51 0.21
4    4 0.39 1.00

CodePudding user response:

Based on the condition showed in OP's post, use case_when. Also, for multiple elements, instead of ==, use %in%

library(dplyr)
df %>%
   mutate(var2 = case_when(
    # if var1 is not equal to 1 or 2, 
    #then var2 equals its original value
     !var1  %in% 1:2 ~ var2,
    # var1 equals 1 or 2, and var3 equals 1, 
    #then var2 equals its original value
   var1 %in% 1:2 & var3 == 1 ~ var2, 
   # otherwise equals 1
   TRUE ~ 1))

-output

  var1 var2 var3
1    1 0.35 1.00
2    2 1.00 0.11
3    3 0.51 0.21
4    4 0.39 1.00

CodePudding user response:

Here is a shorter version of ifelse:

library(dplyr)

df %>% 
  mutate(var2 = ifelse(var1 > 2 | var3 == 1, var2, 1)) %>% 
  as_tibble()
   var1  var2  var3
  <dbl> <dbl> <dbl>
1     1  0.35  1   
2     2  1     0.11
3     3  0.51  0.21
4     4  0.39  1  
  •  Tags:  
  • r
  • Related