0

I would like to replace "(?)" in a dataframe into "1" using str_replace, but it doesn't work.

x <- data.frame(c("1", "(?)", "2"))
 colnames(x)<-c("name")
 x %>%
 mutate(name = stringr::str_replace(name, pattern = "(?)", replacement = "1"))

Error: Problem with `mutate()` column `name`.
i `name = stringr::str_replace(name, pattern = "(?)", replacement = "1")`.
x Syntax error in regexp pattern. (U_REGEX_RULE_SYNTAX, context=`(?)`)
marie
  • 315
  • 1
  • 9
  • 1
    Use `fixed` - `x %>% mutate(name = stringr::str_replace(name, pattern = fixed("(?)"), replacement = "1"))` `?` has a special meaning in regex. – Ronak Shah Jul 15 '21 at 05:46
  • 1
    basically you have to escape the character that have special meaning. In this case both `?` and `()` are special in regex. One means "the preceding item zero or one times" (`?`) the other meaning "exactly what I've written here" `()`. To avoid this you can use `\\ ` to escape the characters, or the `fixed` function as Ronak suggested. Eg: `\\(\\?\\)` – Oliver Jul 15 '21 at 06:27

0 Answers0