Extract first word

前端 未结 3 614
误落风尘
误落风尘 2021-01-06 15:29

I have the following data frame dat :

brand (column name)
Channel clothes
Gucci perfume
Channel shoes
LV purses
LV scarves

And I want to cr

相关标签:
3条回答
  • 2021-01-06 15:43

    I prefer the tidyverse approach.

    With this dataset:

    library(tidyverse)
    
    df <- tribble(
      ~brand,
      "Channel clothes",
      "Gucci perfume",
      "Channel shoes",
      "LV purses",
      "LV scarves"
    )
    

    We can separate the column with the following:

    df %>% 
      separate(brand, into = c("brand", "item"), sep = " ")
    

    Which returns:

    # A tibble: 5 x 2
        brand    item
    *   <chr>   <chr>
    1 Channel clothes
    2   Gucci perfume
    3 Channel   shoes
    4      LV  purses
    5      LV scarves
    
    0 讨论(0)
  • 2021-01-06 15:46

    We can use the word from stringr

    library(stringr)
    word(df$brand, 1)
    #[1] "Channel" "Gucci"   "Channel" "LV"      "LV"     
    
    0 讨论(0)
  • 2021-01-06 16:03

    This should do it.

    dat <- data.frame(Brand = c('Channel clothes',
                               'Gucci perfume',
                               'Channel shoes',
                               'LV purses',
                               'LV scarves'))
    brand <- sub('(^\\w+)\\s.+','\\1',dat$Brand)
    #[1] "Channel" "Gucci"   "Channel" "LV"      "LV" 
    
    0 讨论(0)
提交回复
热议问题