str_replace_all: unexpected behaviour
Hello,
I'm experiencing some unexpected behaviour from str_replace_all.
Here is my problem:
# Create dataframe
df <- tibble(competitor_id = c(1, 5))
# Named vector used in string replacements
id_rpl <- c("1" = "Philly 5 star", "5" = "senor_cactus")
# Mutate dataframe / new column
mutate(df, competitor_name = str_replace_all(competitor_id, id_rpl))
This produces the output
competitor_id competitor_name
<dbl> <chr>
1 Philly senor_cactus star
5 senor_cactus
My problem with the output is "senor_cactus" has replaced the "5" within the "Philly 5 star" string. The replace all description is taken quite literally, almost recursively. And, replaces the original "5" within the competitor_id column, but also replaces the "5" within the string that replaces "1".
Is this intended behaviour? - Just thought i'd mention it, because it doesn't seem right.
Thanks
can't speak for the package author(s), but a solution could be to add some metacharacters to your patterns.
id_rpl <- c("1" = "Philly 5 star", "^5$" = "senor_cactus")
competitor_id competitor_name
<dbl> <chr>
1 1 Philly 5 star
2 5 senor_cactus
Thanks @werkstattcodes. Interesting blog, btw.
Yeah, the replacements happen serially so you'll either need to use a more specific regexp like @werkstattcodes suggests, or change the order of the replacements.