Match and replace words in char-vector

Hi there. I have a vector with text lines in it, like this:

text<-c("Seat 1: 7e7389e3 ($2 in chips)","Seat 3: 6786517b ($1.67 in chips)","Seat 4: 878b0b52 ($2.16 in chips)","Seat 5: a822375 ($2.37 in chips)","Seat 6: 7a6252e6 ($2.51 in chips)")

And I have to replace some words with other words, that i have in a dataframe like this:

df<-data.frame(codigo=c("7e7389e3","6786517b","878b0b52","a822375","7a6252e6"),
name=c("lucas","alan","ivan","lucio","donald"))

So I would like to 1) Grab the first line of "text" 2) Check if there is any word to replace in df 3) Replace it 4) Do the same with the next "text" line and so on. In order to have something like this:

[1] "Seat 1: lucas ($2 in chips)"
[2] "Seat 3: alan ($1.67 in chips)"
[3] "Seat 4: ivan ($2.16 in chips)"
[4] "Seat 5: lucio ($2.37 in chips)"
[5] "Seat 6: donald ($2.51 in chips)"

There is any formula to do this?

1 Like

You can do it like this

library(stringr)

text <- c("Seat 1: 7e7389e3 ($2 in chips)","Seat 3: 6786517b ($1.67 in chips)","Seat 4: 878b0b52 ($2.16 in chips)","Seat 5: a822375 ($2.37 in chips)","Seat 6: 7a6252e6 ($2.51 in chips)")

df <- data.frame(codigo=c("7e7389e3","6786517b","878b0b52","a822375","7a6252e6"),
                 name=c("lucas","alan","ivan","lucio","donald"))

replace <- df$name
names(replace) <- df$codigo

str_replace_all(text, replace)
#> [1] "Seat 1: lucas ($2 in chips)"     "Seat 3: alan ($1.67 in chips)"  
#> [3] "Seat 4: ivan ($2.16 in chips)"   "Seat 5: lucio ($2.37 in chips)" 
#> [5] "Seat 6: donald ($2.51 in chips)"

Created on 2020-10-30 by the reprex package (v0.3.0.9001)

Thank you! That is exactly what I need! And is really simple.

Thank you!!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.