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

How to conditionally fill a cell based on two conditions in R using dplyr

I’ve done this in Base a bunch by manually entering the conditions that need to be met in order to set a new value of a new cell, but I really want to automate the process using dplyr.

This is the problem I currently have:
I have about 50 different places (only 3 in the code below), each with their own distance. I want to be able to set a segment value (Lets say ‘a’ ‘b’ or ‘c’) based on the values in the place and distance column. Note that there are repeating distance values.

DF <- data.frame(place = c(rep('x',10), rep('y', 5), rep('z',5)), distance = c(0:9,5:9,5:9), segment = rep(NA,20))

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

So, if something is at place ‘x’ and is above 0, it will have segment ‘a’. If something is at place ‘y’ and is above 5, it will have segment ‘b’. Places ‘z’ above 5 will have segment ‘c.’

In Base R, I would do this like this:
DF$segment[DF$place == 'x' & DF$distance > 0] <- 'a'

I just want to know if there was a dplyr way to do it.

>Solution :

This should work:

DF %>% 
  mutate(segment = case_when((place == "x" & distance > 0) ~ "a",
                             (place == "y" & distance > 5) ~ "b",
                             (place == "z" & distance > 5) ~ "c",
                             .default = "NA"))

If there is no match it will fill it up with NA. You can change that if you want.

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