Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement of column values based on a named vector

Tags:

r

tidyverse

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  
like image 669
Junitar Avatar asked Oct 24 '25 05:10

Junitar


2 Answers

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    
like image 59
Ronak Shah Avatar answered Oct 26 '25 22:10

Ronak Shah


We can also use data.table

library(data.table)
setDT(df)[, col1 := vec[as.character(col)]]
like image 25
akrun Avatar answered Oct 26 '25 22:10

akrun