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
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
We can use the word
from stringr
library(stringr)
word(df$brand, 1)
#[1] "Channel" "Gucci" "Channel" "LV" "LV"
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"