2

I want to replace _ with \_ in a string.

Test <- 
  c(".model", "sigma2", "log_lik", "AIC", "AICc", "BIC", "ar_roots", 
"ma_roots")

library(stringr)

Test %>% 
  str_replace_all(string = ., pattern = "_", replacement = "\_")

Error: '\_' is an unrecognized escape in character string starting ""\_"

Any hint?

MYaseen208
  • 22,666
  • 37
  • 165
  • 309

1 Answers1

2

You can use -

stringr::str_replace_all(Test, pattern = "_", replacement = "\\\\_")

#[1] ".model"     "sigma2"     "log\\_lik"  "AIC"     "AICc"       "BIC"       
#[7] "ar\\_roots" "ma\\_roots"

While printing \ is escaped with another \ so you see two backslash. To see actual string use cat

cat(stringr::str_replace_all(Test, pattern = "_", replacement = "\\\\_"))

#.model sigma2 log\_lik AIC AICc BIC ar\_roots ma\_roots

Or with gsub -

gsub("_", "\\\\_", Test)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213