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:
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>