# NOT RUN { # Newly created variables are available immediately mtcars %>% as_tibble() %>% mutate( cyl2 = cyl * 2, cyl4 = cyl2 * 2 ) # You can also use mutate() to remove variables and # modify existing variables mtcars %>% as_tibble() %>% mutate( mpg = NULL, disp = disp * 0.0163871 # convert to litres ) # window functions are useful for grouped mutates mtcars %>% group_by(cyl) %>% mutate(rank = min_rank(desc(mpg))) # see `vignette("window-functions")` for more details # You can drop variables by setting them to NULL mtcars %>% mutate(cyl = NULL) # mutate() vs transmute -------------------------- # mutate() keeps all existing variables mtcars %>% mutate(displ_l = disp / 61.0237) # transmute keeps only the variables you create mtcars %>% transmute(displ_l = disp / 61.0237) # mutate() supports quasiquotation. You can unquote quosures, which # can refer to both contextual variables and variable names: var <- 100 as_tibble(mtcars) %>% mutate(cyl = !!quo(cyl * var)) # }
Run the code above in your browser using DataCamp Workspace