Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
Dannyzhd opened this issue Oct 5, 2023 · 1 comment
Closed

Comments

@Dannyzhd
Copy link

Dannyzhd commented Oct 5, 2023

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.

@Dannyzhd Dannyzhd changed the title Using a function as value for replacement argument in str_replace_all() Using a function as value for replacement argument in str_replace_all() Oct 5, 2023
@hadley
Copy link
Member

hadley commented Oct 31, 2023

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.

@hadley hadley closed this as completed Oct 31, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants