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

Marta picture Marta · Feb 14, 2014 · Viewed 75.8k times · Source

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.

Answer

Richie Cotton picture Richie Cotton · Feb 14, 2014

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"