Replace text in one data-frame using a look up to another data-frame

Viewed 1305

I have the task of searching through text, replacing peoples names and nicknames with a generic character string.

Here is the structure of my data frame of names and corresponding nicknames:

names <- c("Thomas","Thomas","Abigail","Abigail","Abigail")
nicknames <- c("Tom","Tommy","Abi","Abby","Abbey")
df_name_nick <- data.frame(names,nicknames)

Here is the structure of my data frame containing text

text_names <- c("Abigail","Thomas","Abigail","Thomas","Colin")
text_comment <- c("Tommy sits next to Abbey","As a footballer Tommy is very good","Abby is a mature young lady","Tom is a handsome man","Tom is friends with Colin and Abi")
df_name_comment <- data.frame(text_names,text_comment)

Giving these dataframes

df_name_nick:

names nicknames
1  Thomas       Tom
2  Thomas     Tommy
3 Abigail       Abi
4 Abigail      Abby
5 Abigail     Abbey

df_name_comment:

text_names                       text_comment
1    Abigail           Tommy sits next to Abbey
2     Thomas As a footballer Tommy is very good
3    Abigail        Abby is a mature young lady
4     Thomas              Tom is a handsome man
5      Colin  Tom is friends with Colin and Abi

I am looking for a routine that will search through each row of df_name_comment and use the df_name_comment$text_names to look up the corresponding nickname from df_name_nick and replace it with XXX. Note for each person's name there can be several nicknames. Note that in each text comment, only the appropriate name for that row is replaced, so that we would get this as output:

Abigail "Tommy sits next to XXX"
Thomas  "As a footballer, XXX is very good"
Abigail "XXX is a mature young lady"
Thomas  "XXX is a handsome man"
Colin   "Tom is friends with Colin and Abi"

I’m thinking this will require a cunning combination of gsubs, matches and apply functions (either mapply, sapply, etc)

I've searched on Stack Overflow for something similar to this request and can only find very specific regex solutions based on data frames with unique row elements, and not something that I think will work with generic text lookups and gsubs via multiple nicknames.

Can anyone please help me solve my predicament? With thanks

Nevil (newbie R programmer since Jan 2017)

3 Answers
Related