Search code examples
rdataframedplyrtidyverserecode

Recode column of character variables in one data frame with numeric values in another data frame


I have the following dataframes:

df <- data.frame(x=c('a', 'b', 'c'), y=c(.1,.2,.3))
xev_values <- data.frame(a=.01, b=.02, c=.03)

How do I recode the character variables in the x column of df with the numeric values in xev_values so that I have a new dataframe?

new_df <- data.frame(xev=c(.01,.02,.03), y=c(.1,.2,.3))

I see how to do this "manually" with recode:

new_df <- data.frame(xev=recode(df$x, 'a'=.01, 'b'=.02, 'c'=.03), y=df$y)

Solution

  • We can convert xev_values to long-format, conduct a join, and then select the columns.

    library(tidyverse)
    
    df2 <- df %>%
      left_join(xev_values %>% gather(x, xev), by = "x") %>%
      select(xev, y)
    df2
    #    xev   y
    # 1 0.01 0.1
    # 2 0.02 0.2
    # 3 0.03 0.3