Haza
Haza

Reputation: 13

R remove \\n in sentence

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

Answers (2)

thus__
thus__

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

Tim Biegeleisen
Tim Biegeleisen

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

Related Questions