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

trouble replacing string values across multiple columns with values from a single column in separate dataframe

I’m trying to replace some values across multiple columns of a dataframe by matching them to other values in a single list:

#data frame of medical codes
code1 <- c('T432', 'T432', 'T432', 'T432')
code2 <- c('T492', 'T405', 'T424', 'J81')
code3 <- c('T509', '', 'R99', '')
code_df <- data.frame(code1, code2, code3)

#data frame of code description
description <- c('Cholera', 'Salmonella', 'Typhoid ', 'Psoriasis', 'Other malady', 'Fever', 'Acute Pain')
code <- c('T432', 'T832', 'T405', 'T424', 'J81', 'R99', 'T492' )
description_df <- data.frame(description, code)

#me trying to replace the code with the corresponding description
code_df[1:3] <- sapply(unlist(code_df[1:3]), function(x) description_df$description[x == description_df][2])

This is just producing a code_df where all values are NA and no descriptions are populated.

Desired result:

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

Code1       Code2            Code3
Cholera     Acute Pain       
Cholera     Typhoid 
Cholera     Psoriasis        Fever
Cholera     Other malady

Thanks in advance.

>Solution :

With match:

code_df[] <- description_df$description[match(unlist(code_df), description_df$code)]

    code1        code2 code3
1 Cholera   Acute Pain  <NA>
2 Cholera     Typhoid   <NA>
3 Cholera    Psoriasis Fever
4 Cholera Other malady  <NA>
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