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

Filter out individuals who developed diseases in a certain sequence

I have a data frame – each individual has multiple visits. I want to filter out patients who had disease 2 after disease 1. In this case, I would pick out ID 2 & 4.

ID <- c(1,1,2,2,2,3,3,3,4,4,4,4,5,5)
Visit <- c(1,2,1,2,3,1,2,3,1,2,3,4,1,2)
Disease <- c(2,2,1,2,1,1,1,1,1,1,1,2,2,1)
df <- data.frame(ID, Visit, Disease)

>Solution :

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

A dplyr solution:

library(dplyr)

df |> 
  filter(Disease == 1 & lead(Disease) == 2, .by = ID) |> 
  pull(ID)

Result:

[1] 2 4
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