Get rid of parts after the space in vector's string elements

Viewed 46

I have a vector which consists of a list of strings, which are the combinations of first name and initials, I want to get rid of the initials

tried sub() and strsplit() but didn't work

name <- data.frame(c("Jones B", "Mike M", "Goods R.I"))

"Jones" "Mike" "Goods"
2 Answers

We can use sub to match one or more space (\\s+) followed by characters (.*) and replace with blanks ("")

sub("\\s+.*", "", name[[1]])
#[1] "Jones" "Mike"  "Goods"

In case if we need compactness

library(stringr)
word(name[[1]], 1)
#[1] "Jones" "Mike"  "Goods"

Assuming you want the word before the first space, you could also use the stringi package:

library(stringi)
stri_extract_first_words(c("Jones B", "Mike M", "Goods R.I"))
[1] "Jones" "Mike"  "Goods"
Related