I have a dataframe of patient IDs and their various medications. Their medications are each listed in the format "name,code,class,dose" in one string separated by commas. Code for a sample dataframe below:
id <- c(1,2,3)
med1 <- c("Penicillin,1,Antibiotic,5mg","Fluoxetine,5,Antidepressant,20mg","Olanzapine,9,Antipsychotic,2mg")
med2 <- c("Aspirin,4,Blood thinner,81mg",NA,"Lisinopril,3,Antihypertensive,10mg")
med3 <- c(NA,NA,"Amlodipine,2,Antihypertensive,5mg")
meds <- data.frame(id, med1, med2, med3)
meds
However, I want to separate these out by each category, so that it would look like:
meds2 <- meds %>% separate(med1, c('med_name1', 'med_code1', "med_class1", "med_dose1"), sep=",") %>% separate(med2, c('med_name2', 'med_code2', "med_class2", "med_dose2"), sep=",") %>% separate(med3, c('med_name3', 'med_code3', "med_class3", "med_dose3"), sep=",")
meds2
I am able to do this with the code I included, but I have to manually write out the separate function for every single medication. In my actual dataset, some patients have over 100 medications, so I would not be able to do this. I tried to write a for loop using the separate function but cannot get it to work:
meds <- for(i in 1:3){
separate(meds2[i+1], c(paste0("med_name", i), paste0("med_code", i), paste0("med_class", i), paste0("med_dose", i), sep=","))
}
Does anyone know where I might be going wrong or know of another approach to achieve this? Thanks so much!

