remove all line breaks (enter symbols) from the string using R

RRegexLine Breaks

R Problem Overview


How to remove all line breaks (enter symbols) from the string?

my_string <- "foo\nbar\rbaz\r\nquux"

I've tried gsub("\n", "", my_string), but it doesn't work, because new line and line break aren't equal.

R Solutions


Solution 1 - R

You need to strip \r and \n to remove carriage returns and new lines.

x <- "foo\nbar\rbaz\r\nquux"
gsub("[\r\n]", "", x)
## [1] "foobarbazquux"

Or

library(stringr)
str_replace_all(x, "[\r\n]" , "")
## [1] "foobarbazquux"

Solution 2 - R

I just wanted to note here that if you want to insert spaces where you found newlines the best option is to use the following:

gsub("\r?\n|\r", " ", x)

which will insert only one space regardless whether the text contains \r\n, \n or \r.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartaView Question on Stackoverflow
Solution 1 - RRichie CottonView Answer on Stackoverflow
Solution 2 - RMidnighterView Answer on Stackoverflow