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

Convert cell to blank based on time condition

I have a dataframe that looks like this:

> dput(df)
structure(list(Person_ID = c(123L, 123L), Disease_Name = c("Heart Disease", 
"Lung Disease"), Disease_start = c("4/11/17", "4/11/17"), Procedure_start = c("4/11/18", 
"4/11/16")), class = "data.frame", row.names = c(NA, -2L))

I want to restructure the dataframe so that:

  • If the Disease_start is BEFORE Procedure_start, then convert Disease_Name to a blank/NA cell
  • If the Disease_start is AFTER Procedure_start, then leave Disease_Name (don’t change anything)

The output dataset should look like this:

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

> dput(df2)
structure(list(Person_ID = c(123L, 123L), Disease_Name = c("", 
"Lung Disease"), Disease_start = c("4/11/17", "4/11/17"), Procedure_start = c("4/11/18", 
"4/11/16")), class = "data.frame", row.names = c(NA, -2L))

Thank you!

>Solution :

Use an ifelse or case_when

library(dplyr)
df %>% 
  mutate(Disease_Name = case_when(Disease_start < Procedure_start ~"", 
      TRUE ~ Disease_Name))

-output

  Person_ID Disease_Name Disease_start Procedure_start
1       123                    4/11/17         4/11/18
2       123 Lung Disease       4/11/17         4/11/16
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