Thank you @ivelasq3 for giving me a starter-mimimal working example(mwe).
With your example unnest works nicely with your mwe, however clinical datasets are different.
Here is a mwe which represents a typical anonymized clinical dataset when it's dumped from the hospital-information-system.
Patient_id is unique to the Patient and appeares per every admission in the dataset. Per admission to the hospital a Patient gets a case number (patient_case) which is unique to the case. The rest of the data - like medication - might change over time and contains duplicates.
Unnest seems unable to cope with several admissions (patient_case) of the same patient (patient_id) to the hospital, so unnest throws an error:
library(tidyr)
library(dplyr)
library(tibble)
patients <- c(1:100)
numbers <- c(1000:1999)
ages <- c(18:90)
sexes <- c("male", "female", "diverse")
patlist <- tibble(
patient_id = patients,
age = sample(ages, 100, replace = TRUE),
sex = sample(sexes, 100, replace = TRUE),
Med_ID = sample(5, 100, replace = TRUE)
)
caselist <- tibble(
patient_case = sample(numbers, 300, replace = TRUE),
patient_id = sample(patients, 300, replace=TRUE)
)
patlist <- left_join(patlist, caselist)
medlist <- tibble(
Med_ID = 1:5,
Med.Immunsupressive = list(
c("Tacrolimus", "Prednisone"),
c("Cyclosporine"),
character(0),
c("Azathioprine", "Mycophenolate", "Prednisone"),
NULL
),
Med.Antibiotic = list(
c("Amoxicillin"),
character(0),
c("Azithromycin", "Doxycycline"),
NULL,
c("Ciprofloxacin")
),
Med.Antihypertensive = list(
c("Lisinopril", "Amlodipine"),
c("Metoprolol"),
c("Losartan"),
character(0),
c("Hydrochlorothiazide")
)
)
patlist <- left_join(patlist, medlist) %>% select(-Med_ID)
patlist %>% unnest()
I've tried several approaches but didn't figure out how to solve this. Is there a tidyverse-way to solve this problem?
Thanks
nielsson