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

str_replace_all: unexpected behaviour #545

Open
shaggycamel opened this issue Apr 11, 2024 · 2 comments
Open

str_replace_all: unexpected behaviour #545

shaggycamel opened this issue Apr 11, 2024 · 2 comments

Comments

@shaggycamel
Copy link

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

@werkstattcodes
Copy link

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

@shaggycamel
Copy link
Author

Thanks @werkstattcodes. Interesting blog, btw.

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