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 Answers1

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?"
jdobres
  • 11,339
  • 1
  • 17
  • 37
  • 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? – ThreatworkAnalyst Sep 28 '22 at 18:30
  • Can you provide the first few rows of the data frame via `dput(head(df))`? – jdobres Sep 28 '22 at 18:34
  • 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`. – jdobres Sep 28 '22 at 18:35
  • structure(list(df = "c(\"NULL\", \"NULL\", \"{\\\"4\\\":[\\\"[\\\\\\\"Morals right down \\\\\\\\nthe drain?\\\\\\\"]\\\"]}\" – ThreatworkAnalyst Sep 28 '22 at 18:37
  • I think you left off some of the `dput` output. It would be best if you could edit your original post to include it. – jdobres Sep 28 '22 at 18:45
  • I got it finally! It took this, df$text_info <- gsub(r'(\\\\n)', '', df$text_info), thank you so much for the help! – ThreatworkAnalyst Sep 28 '22 at 18:49
  • Great! If this answer worked for you, please mark it as correct, and optionally, upvote. – jdobres Sep 28 '22 at 18:54
  • Done, I just can't upvote because I'm new :/ – ThreatworkAnalyst Sep 28 '22 at 18:58