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

Grouping by a factor, return 1 if characters match on any row – R

My dataset is grouped by RunID with a different row for every diagnosis the patient has.

I’m trying to create a new variable for if a particular diagnosis (e.g. pneumonia) appears on any row within that RunID.

I tried using any but received the error message
Caused by warning in `any()`: ! coercing argument of type 'character' to logical

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

Any suggestions on how to fix it? What I tried was:

data %>%
  group_by(RunID) %>%
  mutate(Pneumonia = ifelse(any(diagnosis="Pneumonia"),1,0))

reprex:

library(tibble)
library(dplyr)

data <- tribble(
  ~RunID, ~diagnosis,
  "A12", "Pneumonia",
  "A12", NA,
  "A12", "copd",
  "A12", "CF",
)

data$RunID<-as.factor(data$RunID)

desired <- tribble(
  ~RunID, ~diagnosis, ~Pneumonia,
  "A12", "Pneumonia", 1,
  "A12", NA, 1,
  "A12", "copd", 1,
  "A12", "CF", 1
)

>Solution :

We may need == instead of = in any(diagnosis="Pneumonia") but, it can be also done as

library(dplyr) # version >= 1.1.0
data %>% 
  mutate(pneumonia = +('Pneumonia' %in% diagnosis), .by = 'RunID')
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