I think there were some slight errors in fstrueb's solution. See below for two solutions. I prefer using the functions in the stringr
package for patterns. All the functions begin with str_
library(tidyverse)
# tidyverse solution
mgtb<-tbl_df(mpg) %>%
mutate(trans.grp = if_else(str_detect(trans, "auto"), "A", "M"))
mgtb %>%
count(trans, trans.grp)
#> # A tibble: 10 x 3
#> trans trans.grp n
#> <chr> <chr> <int>
#> 1 auto(av) A 5
#> 2 auto(l3) A 2
#> 3 auto(l4) A 83
#> 4 auto(l5) A 39
#> 5 auto(l6) A 6
#> 6 auto(s4) A 3
#> 7 auto(s5) A 3
#> 8 auto(s6) A 16
#> 9 manual(m5) M 58
#> 10 manual(m6) M 19
#similar solution to fstrueb
mgtb2<-tbl_df(mpg) %>%
mutate(trans.grp = if_else(grepl("auto", trans), "A", "M"))
mgtb2 %>%
count(trans, trans.grp)
#> # A tibble: 10 x 3
#> trans trans.grp n
#> <chr> <chr> <int>
#> 1 auto(av) A 5
#> 2 auto(l3) A 2
#> 3 auto(l4) A 83
#> 4 auto(l5) A 39
#> 5 auto(l6) A 6
#> 6 auto(s4) A 3
#> 7 auto(s5) A 3
#> 8 auto(s6) A 16
#> 9 manual(m5) M 58
#> 10 manual(m6) M 19
Created on 2020-01-11 by the reprex package (v0.3.0)