Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace strings in variable using lookup vector

I have a dataframe df with a character variable and the fromvec and tovec.

df <- tibble(var = c("A", "B", "C", "a", "E", "D", "b"))

fromvec <- c("A", "B", "C")

tovec <- c("X", "Y", "Z")

Use strings in fromvec, check them in df and then replace them with the corresponding strings in tovec so that "A" in df gets replaced with "X", "B" with "Y" and so on to get the desired_df.

desired_df <- tibble(var = c("X", "Y", "Z", "X", "E", "D", "Y"))

I tried following, but not getting the desired result!

from_vec <- paste(fromvec, collapse="|") 
to_vec <- paste(tovec, collapse="|") 

undesired_df <- df %>% 
  mutate(var = str_replace(str_to_upper(var), from_vec, to_vec))

i.e. this

tibble(var = c("X|Y|Z", "X|Y|Z", "X|Y|Z", "X|Y|Z", "E", "D", "X|Y|Z"))

How can I get the desired_df?

like image 307
Geet Avatar asked Jul 21 '26 15:07

Geet


2 Answers

You could use chartr :

df$var <- chartr(paste(fromvec,collapse=""),
                 paste(tovec,collapse=""),
                 toupper(df$var))
# # A tibble: 7 x 1
#   var  
#   <chr>
# 1 X    
# 2 Y    
# 3 Z    
# 4 X    
# 5 E    
# 6 D    
# 7 Y    

Or we can use recode

library(dplyr)
df$var <- recode(toupper(df$var), !!!setNames(tovec,fromvec))

If you really want to use str_replace you could do:

library(purrr)
library(stringr)
df$var <- reduce2(fromvec, tovec, str_replace, .init=toupper(df$var))
like image 143
Moody_Mudskipper Avatar answered Jul 23 '26 06:07

Moody_Mudskipper


The correct way to do this with stringr is with str_replace_all:

mutate(df,str_replace_all(str_to_upper(var),setNames(tovec, fromvec)))

(thanks, @Moody_Mudskipper!)

like image 28
iod Avatar answered Jul 23 '26 06:07

iod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!