Add column to a data frame defined by existing column

install.packages("GISTools")
install.packages("ggplot2")
library(ggplot2)
ggplot(data=mpg)
install.packages("tidyverse")
library(tidyverse)
mgtb<-tbl_df(mpg)

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

mgtbl %>% dplyr::mutate(trans.grp = ifelse(grepl(pattern = 'auto', x = trans), 'A', 'M'))

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"

this didnt work for me :frowning:

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)

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...

thank you so much it worked ! thank you too fstrueb.

Could you tell me what %>% does ?

This comes from the magrittr package and is a pipe operator. You can find details here: https://magrittr.tidyverse.org/

This package is loaded whenever you load the tidyverse package.

That's not quite correct: magrittr is not loaded with the tidyverse package. The %>% pipe operator is loaded, but not the package itself.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.