Search code examples
rsubstrbackslash

How to ignore escape character while using substr function in R


There is a string variable x

x <- "aa\xbbcc"

I want to use

y <- substr(x, 1, 3)

to extract the first three character "aa\".

However, "\x" is an escape character. Therefore an error message showed:

Error during wrapup: invalid regular expression '\', reason 'Trailing backslash'

I tried to use

x <- gsub("\\", "/", x)

to replace "\", but it didn't work and showed:

Error during wrapup: invalid regular expression '\', reason 'Trailing backslash'

How to solve this problem? thanks


Solution

  • \xbb inserts the ASCII character >> into the string. \xbb is hexadecimal notation for the decimal value 187. To delete this character, do this:

    gsub("\xbb","",x)
    

    Then you can use substr on the resulting string.