2

Consider the following named vector vec and tibble df:

vec <- c("1" = "a", "2" = "b", "3" = "c")
df <- tibble(col = rep(1:3, c(4, 2, 5)))

df
# # A tibble: 11 x 1
#      col
#    <int>
#  1     1
#  2     1
#  3     1
#  4     1
#  5     2
#  6     2
#  7     3
#  8     3
#  9     3
# 10     3
# 11     3

I would like to replace the values in the col column with the corresponding named values in vec.

I'm looking for a tidyverse approach, that doesn't involve converting vec as a tibble.

I tried the following, without success:

df %>% 
  mutate(col = map(
    vec,
    ~ str_replace(col, names(.x), .x)
  ))

Expected output:

# A tibble: 11 x 1
   col    
   <chr>
 1 a    
 2 a    
 3 a    
 4 a    
 5 b    
 6 b    
 7 c    
 8 c    
 9 c    
10 c    
11 c  
Junitar
  • 905
  • 6
  • 13

2 Answers2

4

You could use col :

df$col1 <- vec[as.character(df$col)]

Or in mutate :

library(dplyr)
df %>% mutate(col1 = vec[as.character(col)])
#   col col1 
#   <int> <chr>
# 1     1 a    
# 2     1 a    
# 3     1 a    
# 4     1 a    
# 5     2 b    
# 6     2 b    
# 7     3 c    
# 8     3 c    
# 9     3 c    
#10     3 c    
#11     3 c    
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

We can also use data.table

library(data.table)
setDT(df)[, col1 := vec[as.character(col)]]
akrun
  • 874,273
  • 37
  • 540
  • 662