Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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?"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading