Better way to add the grouping variable in my dataset

Viewed 64

I am trying to find a better solution to group my records. Right now I am using the following code to group the rows into different groups. Can someone tell me what are the other ways to achieve the same result?

Items<- rep(c("cleats","whistle","VAR","Penalty","Bat","Pink Ball","White Ball","Super-Over","Hoops","Men's Rugby","Women's rugby"),5) 

dt <- data.frame(Items)  
dt$Classification=NA

classification_list=list(c("dt[,'Items'] %in% c('cleats','whistle','VAR','Penalty')","Football"),
                         c("dt[,'Items'] %in% c('Bat','Pink Ball','White Ball','Super-Over')","Cricket"),
                         c("grepl('Rugby',dt[,'Items'])|grepl('rugby',dt[,'Items'])","Rugby"),
                         c("is.na(dt[,'Classification'])","Other Sports"))

for (i in 1:length(classification_list)){
     dt$Classification = ifelse(eval(parse( text = paste0("(",classification_list[[i]][1],")","& is.na(dt$Classification)"))),
                              classification_list[[i]][2],
                             dt$Classification) }
1 Answers

dplyr (and stringr) solution would look something like this.

tibble(Items) %>%
mutate(
  Classification = case_when(
    Items %in% c('cleats','whistle','VAR','Penalty') ~ "Football",
    Items %in% c('Bat','Pink Ball','White Ball','Super-Over') ~ "Cricket",
    str_detect(Items, "Rugby|rugby") ~ "Rugby",
    T ~ "Other Sports"
  )
)
Related