Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove all characters that lie between blanks (white spaces) in R string?

Suppose you have a character string "The Big Dog" and you would like to remove all characters that lie between the blanks (white spaces), so you end up with "The Dog". Note that in the actual code the "Big" is dynamic and the string between the white spaces can be formed by different sequences of continuous characters, so searching/replacing for "Big" is not a solution. How would this be done, preferably in base R but as second choice using stringr package?

Here is my futile attempt in base R:

test <- c("The Big Dog")
test1 <- sub(" " ".*" " ", "", test)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

test <- c("The Big Dog", "A Giant and Enormous Dog")
sub(" .* ", " ", test)
#[1] "The Dog" "A Dog"  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading