1

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)

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Ronak's answer works well, too, but this one fits nicely in my tidyverse workflow.
2

If you have only one row in xev_values we can compare x column in df with that of names(xev_values) and extract the corresponding column value.

df$x <- unlist(xev_values[1, match(df$x, names(xev_values))])

df 
#     x   y
#1 0.01 0.1
#2 0.02 0.2
#3 0.03 0.3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.