Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove n number of identical characters from string in R

Tags:

r

gsub

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?

like image 901
icedcoffee Avatar asked Sep 02 '25 03:09

icedcoffee


1 Answers

We can use + to signify one or more repetitions

gsub("\n+", " ", mystring)
[1] "hello i am a dog"
like image 78
akrun Avatar answered Sep 05 '25 01:09

akrun