Hi everyone. I want to add a column with "trans.grp" to the data set. The column should have the content "A" or "M" referring to the already existing column trans which defines if a car is manual or automatic. can someone please help me ?
thank to everyone
Basically, you're logically checking (ifelse) if your column "trans" contains (grepl) the word auto, only then the new column will contain "A", otherwise "M"
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
Yep, you're right, I misplaced the closing parenthesis in the 'grepl' function and mixed up the pattern and col. Updated my post to reflect the changes. Although I'm never sure whether I need to use .$trans in grepl or if trans is just enough for grepl to find the right column...