remove all line breaks (enter symbols) from the st

2020-02-08 04:15发布

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

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

Thank you!

标签: r line break
2条回答
地球回转人心会变
2楼-- · 2020-02-08 04:43

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.

查看更多
戒情不戒烟
3楼-- · 2020-02-08 04:46

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"
查看更多
登录 后发表回答