First entry from string split

后端 未结 5 1965
陌清茗
陌清茗 2020-12-03 04:30

I\'ve got a column people$food that has entries like chocolate or apple-orange-strawberry.

I want to split people$food

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 05:19

    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"
    

提交回复
热议问题