First entry from string split

If you need to extract the first (or nth) entry from each split, use:

word <- c('apple-orange-strawberry','chocolate')

sapply(strsplit(word,"-"), `[`, 1)
#[1] "apple"     "chocolate"

Or faster and more explictly:

vapply(strsplit(word,"-"), `[`, 1, FUN.VALUE=character(1))
#[1] "apple"     "chocolate"

Both bits of code will cope well with selecting whichever value in the split list, and will deal with cases that are outside the range:

vapply(strsplit(word,"-"), `[`, 2, FUN.VALUE=character(1))
#[1] "orange" NA  

Leave a Comment