Error when replacing text in R

I am replacing one text in R using sub.

 x<-"My name is ${name}"
 sub("${name}","Tiger",x)

      

Error message:

Error in sub("${name}", "Tiger", x) : 
  invalid regular expression '${name}', reason 'Invalid contents of {}'

      

The input text has {}, how to fix this error?

+3


source to share


2 answers


Use an argument fixed=TRUE

:



sub("${name}","Tiger",x, fixed=TRUE)
# [1] "My name is Tiger"

      

+7


source


$

, {

and }

must be escaped:



sub("\\$\\{name\\}","Tiger",x)
# [1] "My name is Tiger"

      

+7


source







All Articles