-1

I am trying to find and replace some of the values of a data frame consisting of strings. The simple case like the following works,

library(stringr)
test1 <- c("one", "two", "three")
str_replace_all(string = test1,
                pattern = c('one' = "1ne",
                            'three' = "3ree"))
> [1] "1ne"  "two"  "3ree"

However, a more complicated case like the following isn't working. What am I doing wrong here?

test2 <- c("one (1) x1", "two (2) x2", "three (3) x3")
test2 <- c("one (1) x1", "two (2) x2", "three (3) x3")
str_replace_all(string = test2,
                   pattern = c('one (1) x1' = "X1",
                               'two (2) x2' = "X2"))
> [1] "one (1) x1"   "two (2) x2"   "three (3) x3"
kath
  • 7,624
  • 17
  • 32
small_lebowski
  • 701
  • 7
  • 23
  • 1
    Try '\\' before curly braces in the pattern, e.g. one \\\(1\\\) x1 – warnbergg Jul 04 '19 at 09:07
  • 2
    `str_replace_all` use regular expressions and parenthesis are not interpreted as parenthesis – Clemsang Jul 04 '19 at 09:08
  • 1
    Parenthesis has special meaning in regex you need to escape them or use `fixed`. Possible duplicate https://stackoverflow.com/questions/27721008/how-do-i-deal-with-special-characters-like-in-my-regex – Ronak Shah Jul 04 '19 at 09:14

1 Answers1

1

Use fixed to avoid regex matching

str_replace_all(string = test2,
                pattern = fixed(c('one (1) x1' = "X1",
                          'two (2) x2' = "X2")))
# [1] "X1"           "X2"           "three (3) x3"
fmarm
  • 4,209
  • 1
  • 17
  • 29