I have a string in R where the words are interspaced with a random number of character \n
:
mystring = c("hello\n\ni\n\n\n\n\nam\na\n\n\n\n\n\n\ndog")
I want to replace n number of repeating \n
elements so that there is only a space character between words. I can currently do this as follows, but I want a tidier solution:
mystring %>%
gsub("\n\n", "\n", .) %>%
gsub("\n\n", "\n", .) %>%
gsub("\n\n", "\n", .) %>%
gsub("\n", " ", .)
[1] "hello i am a dog"
What is the best way to achieve this?
We can use +
to signify one or more
repetitions
gsub("\n+", " ", mystring)
[1] "hello i am a dog"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With