0

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:

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!

3 Answers3

0

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")
Eric
  • 1,381
  • 9
  • 24
0

One way you can use is the merge() function from base R:

df_output <- merge(
, df_example           # first data
, df_code              # second data 
, by.x = "level"       # column name of first data to merge by 
, by.y = "level_code"  # column name of second data to merge by 
, sort = F             # the order should same as first data
)


#rename the column names of the merged data

names(df_output)<-c("c1_output","c2_output")
df_output

  c1_output c2_output
1        S1        10
2        C2         2
3        T3         6
4        L1         7
S-SHAAF
  • 1,863
  • 2
  • 5
  • 14
0

alternatively you can use the inner_join

want <- df_code %>% inner_join(df_example, by=c('c1'='col'))

Created on 2023-02-25 with reprex v2.0.2

  c1 c2
1 C2  2
2 T3  6
3 L1  7
4 S1 10
jkatam
  • 2,691
  • 1
  • 4
  • 12