tidyverse / stringr

A fresh approach to string manipulation in R

Home Page:https://stringr.tidyverse.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using a function as value for replacement argument in ```str_replace_all()```

Dannyzhd opened this issue · comments

Dear Developer Team,

I recently was utilizing stringr for the following case.

The user would input something like user_input = c("xxx * yyy * zzz", "zzz * mmm * nnn", "zzz"). Essentially I wanted to replace all occurences of "zzz" with my value "ZZZZZ", and all occurences or "xxx" with my value "XXXXX".

The following code(after discussing with GPT) works. But the fact that we are using a function value for replacement argument is kinda confusing to me:

user_input =  c("xxx*yyy*zzz", "zzz*mmm*nnn", "zzz")

# I created a named vector for matching relationship.
name_map <- c("zzz" = "ZZZZZZ", "xxx" = "XXXXX")

# this record the patterns I will be looking for, parsed by logical sign of "|" to indicate the whichever one on the list is eligible for 
# matching.
pattern <- paste(names(name_map), collapse = "|")

# this extracts the value using name as index from the named vector for matching.
replacement <- function(x) name_map[x]

# notice I passed the function I just created as replacement argument here.
user_input_update <- stringr::str_replace_all(user_input, pattern = pattern, replacement = replacement)

user_input_update

I find it counterintuitive as after str_replace_all() finds the terms in user_input that matches the pattern, it surprisingly knows to pass the term as an argument to my replacement argument which is itself a function? I mean normally we would put a customized string for replacement so that str_replace_all() would directly go for replacing all matching terms with that string right?

I wonder if this specific way of using a function as replacement argument is documented somewhere.

Thanks so much in advance for reviewing my question.

Best regards.

It's documented in the documentation for the replacement argument to stringr::str_replace_all(). It's also shown in the examples. This is a pretty advanced feature, but it's handy sometimes.