Home > Enterprise >  In R, replace "\n" (The end-line) with "\" and a "n" (not the end-li
In R, replace "\n" (The end-line) with "\" and a "n" (not the end-li

Time:07-04

In a variable I try to replace the "\n" (end-line) with the characters "" and "n". All this to get a variable where the end-line is replaced by the text "\n" literally.

I tried:

MyText <- gsub("\n", " \\n ", "Line1\nLine2")

But somehow I end up with: "Line1nLine2" As soon I try to replace the end-line I'm not able to get the character "" in my variable.

Tried with str_replace_all, it's the same !

Has anybody an idea ?

Cheers, E

CodePudding user response:

We could use fixed = TRUE

gsub("\n", " \n ", "Line1\nLine2", fixed = TRUE)
[1] "Line1 \n Line2"

or without using the escape on replacement

gsub("\n", " \n ", "Line1\nLine2")
[1] "Line1 \n Line2"

CodePudding user response:

StackOverflow seems to replace the slashes as well ;)

A regex in R usually needs to be escaped twice. For a fixed string, we still need to escape the backslash with another backslash:

gsub("\n", " \\\\n ", "Line1\nLine2")

gsub("\n", " \\n ", "Line1\nLine2", fixed = T)
Viewing output

It might appear that we now have two backslashes, but that's just print() escaping it for us:

> gsub("\n", " \\\\n ", "Line1\nLine2")
[1] "Line1 \\n Line2"
> test <- gsub("\n", " \\\\n ", "Line1\nLine2")
> cat(test)
Line1 \n Line2
> strsplit(test,'')
[[1]]
 [1] "L"  "i"  "n"  "e"  "1"  " "  "\\" "n"  " "  "L"  "i"  "n"  "e"  "2" 
More information

... can be found for instance on the stringr regex vignette in the paragraph Escaping.

  •  Tags:  
  • r
  • Related