Home > Net >  How to replace \\n with a space from dataframe column? (escape sequence)
How to replace \\n with a space from dataframe column? (escape sequence)

Time:09-29

I am trying to replace all "\n" with a space in char strings in a column of data in R but not having much luck. (I also will need to get rid of all single backslashes with nothing but haven't made it that far yet.

An example of a row of column text is:

["Morals right down \\nthe drain?\"]

Here is my code:

df <- read.csv("Text.csv")
df <- df %>% select (text_info) #removing unwanted columns

The following doesn't work it doesn't do anything that I can see:

df  <-gsub("\\n", " ", df$text_info)

This almost works, but leaves one backslash:

df  <-gsub("\\\\n", " ", df$text_info)

Result: ["Morals right down \ the drain?\"]"]}

any help is appreciated.

CodePudding user response:

R 4.0.0 and later support raw strings, which gets around the sometimes confusing need to escape (or double escape) certain characters.

Raw strings are delineated by surrounding the string like so: r'(my_string_here)'. Applying this to your example:

text <- "Morals right down \\nthe drain?"

gsub(r'(\\n)', ' ', text)

[1] "Morals right down  the drain?"
  • Related