Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I know that to remove backslashes is not very hard but I am not able to do that. I have tried the below steps that that won't work. The following is my character:

t1 <- "1\2\3\4\5"

What I have tried is as follows:

t1 <- gsub('\\','', t1)

t1 <- gsub('\\\\','', t1)

str_remove(t1, "\\")

str_remove(t1, "\\\\")

1 Answer

0 votes
by (108k points)

See your 2nd method is correct. A literal backslash in regex in R programming basically requires four backslashes:

t1 <- gsub("\\\\", "", t1)

The reason the above appears to not work is that the string t1 was defined incorrectly. You should have defined it as:

t1 <- "1\\2\\3\\4\\5"

gsub("\\\\", "", t1)

[1] "12345"

A literal backslash in an R character literal requires two backslashes. What you defined originally as t1 is actually a bunch of control characters:

t1 <- "1\2\3\4\5"

Browse Categories

...