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

放肆的年华 提交于 2019-11-27 11:31:56

问题


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!


回答1:


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"



回答2:


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.



来源:https://stackoverflow.com/questions/21781014/remove-all-line-breaks-enter-symbols-from-the-string-using-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!