Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 657
Marta Avatar asked Feb 14 '14 13:02

Marta


People also ask

How do you remove line breaks from a string?

Use the String. replace() method to remove all line breaks from a string, e.g. str. replace(/[\r\n]/gm, ''); . The replace() method will remove all line breaks from the string by replacing them with an empty string.

How do I remove an RN from a string in Python?

Use the str. rstrip() method to remove \r\n from a string in Python, e.g. result = my_str. rstrip() .


2 Answers

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" 
like image 95
Richie Cotton Avatar answered Sep 22 '22 01:09

Richie Cotton


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.

like image 29
Midnighter Avatar answered Sep 23 '22 01:09

Midnighter