First entry from string split

后端 未结 5 1967
陌清茗
陌清茗 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:30

    For example

    word <- 'apple-orange-strawberry'
    
    strsplit(word, "-")[[1]][1]
    [1] "apple"
    

    or, equivalently

    unlist(strsplit(word, "-"))[1].
    

    Essentially the idea is that split gives a list as a result, whose elements have to be accessed either by slicing (the former case) or by unlisting (the latter).

    If you want to apply the method to an entire column:

    first.word <- function(my.string){
        unlist(strsplit(my.string, "-"))[1]
    }
    
    words <- c('apple-orange-strawberry', 'orange-juice')
    
    R: sapply(words, first.word)
    apple-orange-strawberry            orange-juice 
                    "apple"                "orange"
    

提交回复
热议问题