Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ifelse with 3 conditions and 2 outcomes

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)))

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading