You can use the word function from the stringr package. Nothing but the vector x , it returns the first word in the string, where the words are separated by a space.
> x <- c("the quick", "brown dogs were", "lazier than quick foxes") > library(stringr) > word(x) # [1] "the" "brown" "lazier"
And to match the output from your beforeSpace function, we can use setNames
> setNames(word(x), x) # the quick brown dogs were lazier than quick foxes # "the" "brown" "lazier"
Another option is strsplit with sapply instead of vapply
> sapply(strsplit(x, " "), "[", 1) # [1] "the" "brown" "lazier"
source share