I\'ve got a column people$food
that has entries like chocolate
or apple-orange-strawberry
.
I want to split people$food>
I would use sub()
instead. Since you want the first "word" before the split, we can simply remove everything after the first -
and that's what we're left with.
sub("-.*", "", people$food)
Here's an example -
x <- c("apple", "banana-raspberry-cherry", "orange-berry", "tomato-apple")
sub("-.*", "", x)
# [1] "apple" "banana" "orange" "tomato"
Otherwise, if you want to use strsplit()
you can round up the first elements with vapply()
vapply(strsplit(x, "-", fixed = TRUE), "[", "", 1)
# [1] "apple" "banana" "orange" "tomato"