[R] Problem with the str_replace function

phii m@iii@g oii phiiipsmith@c@ phii m@iii@g oii phiiipsmith@c@
Wed Mar 17 01:34:06 CET 2021


I have a problem with the str_replace() function in the stringr package. 
Please refer to my reprex below.

I start with a vector of strings, called x. Some of the strings contain 
apostrophes and brackets. I make a simple replacement as with x1, and 
there is no problem. I make another simple replacement, x2, where the 
pattern string has an apostrophe. Again no problem. Then I make a third 
replacement, x3, where the pattern has opening and closing brackets and 
the function still works fine. Finally I make a replacement where the 
pattern has both an apostrophe and opening and closing brackets and the 
replacement does not work. I tried to solve this by putting backslashes 
before the apostrophe and/or the brackets, but that accomplished 
nothing. I am stumped.

# Reprex for str_replace problem

library(stringr)

x <- c(
   "Clothing and footwear",
   "Women's clothing",
   "Women's footwear (excluding athletic)",
   "Clothing accessories (belts and so on)",
   "Clothing and footwear",
   "Women's clothing",
   "Women's footwear (excluding athletic)",
   "Clothing accessories (belts and so on)"
)
x
x1 <- str_replace(x,
   "Clothing and footwear",
   "Clothing and shoes"
)
x1
x2 <- str_replace(x,
   "Women's clothing",
   "Women's clothing goods"
)
x2
x3 <- str_replace(x,
   "Clothing accessories (belts and so on)",
   "Clothing accessories")
x3
x4 <- str_replace(x,
   "Women's footwear (excluding athletic)",
   "Women's footwear")
x4



More information about the R-help mailing list