1

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.

1 Answer 1

1

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?"
Sign up to request clarification or add additional context in comments.

8 Comments

I can't really tell if this works, it transforms it into a list, which i use df <- data.frame(df) to transform it back into a dataframe, but it comes back as a df of 1 observation and 1 variable looking like the data is corrupted. Any clues?
Can you provide the first few rows of the data frame via dput(head(df))?
From your example, it looks like you're assigning the output of gsub to df itself, whereas I think you want to assign into df$text_info.
structure(list(df = "c(\"NULL\", \"NULL\", \"{\\\"4\\\":[\\\"[\\\\\\\"Morals right down \\\\\\\\nthe drain?\\\\\\\"]\\\"]}\"
I think you left off some of the dput output. It would be best if you could edit your original post to include it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.