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

How to convert a column in a dataframe to a numeric value based on a specific code

I have a column in a dataframe in R that has vertebrae levels coded as characters from C7-S2.

df_example <- data.frame(c("S1", "C2", "T3","L1"))
df_example

I need to convert each row to a numeric value based on a separate dataframe that has the specific value that each level needs to be converted to. It looks similar to this:

c1 <- c("C1","C2","C3","T1","T2","T3","L1","L2","L3","S1","S2")
c2 <- c(1,2,3,4,5,6,7,8,9,10,11)
df_code <- data.frame(c1,c2)
df_code

I would like the final output to look like this:

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

c1_output <- c("S1", "C2", "T3","L1")
c2_output <- c(10,2,6,7)
df_output <- data.frame(c1_output,c2_output)
df_output

However, I am not sure how to do this. Is there some sort of function I could apply to the column in the dataframe to create a new column based on the other dataframe with the specific "codes"? I would appreciate any help – thanks!

>Solution :

same as @zephryl suggested. using your data.

df_example <- data.frame(vertebrae = c("S1", "C2", "T3","L1"))

c1 <- c("C1","C2","C3","T1","T2","T3","L1","L2","L3","S1","S2")
c2 <- c(1,2,3,4,5,6,7,8,9,10,11)
df_code <- data.frame(vertebrae = c1,locs = c2)

library(dplyr)
df_example %>%
  left_join(df_code, by = "vertebrae")
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