Reputation: 13
I want to remove \n in a sentence using R. However, I am unable to remove it. Nothing happen to my sentence. My sentence is UTF-8 encoded, which I get the sentence from read.csv() .
sentence <- "To be there with a samsung phone\\nššš"
str_replace_all(sentence , "[\r\n]" , "")
# [1] To be there with a samsung phone\\nššš
gsub("\r?\n|\r", "", sentence)
# [1] "To be there with a samsung phone\\nššš"
gsub("[\r\n]", "", sentence)
# [1] "To be there with a samsung phone\\nššš"
str_squish(sentence)
# [1] "To be there with a samsung phone\\nššš"
Nothing happen - the \n is not removed. How can I remove it? Thank you in advance!
Upvotes: 0
Views: 161
Reputation: 486
You need to escape the back slash as it is itself an escape character. Try stringr::str_replace(sentence, ā\\nā, ā ā)
. You might need to add a few more backslashes if there are more.
Upvotes: 0
Reputation: 521289
The problem is that \\n
inside an R string literal is not a newline, it is a literal backslash followed by the character n
. You wanted to use this version:
sentence <- "To be there with a samsung phone\nHello World"
sentence
[1] "To be there with a samsung phone\nHello World"
gsub("\r?\n", "", sentence)
[1] "To be there with a samsung phoneHello World"
Upvotes: 1