Learn R Programming

tidyft (version 0.9.20)

mutate: Create or transform variables

Description

mutate() adds new variables and preserves existing ones; transmute() adds new variables and drops existing ones. Both functions preserve the number of rows of the input. New variables overwrite existing variables of the same name.

mutate_when integrates mutate and case_when in dplyr and make a new tidy verb for data.table. mutate_vars is a super function to do updates in specific columns according to conditions.

If you mutate a data.table, it is forever changed. No copies made, which is efficient, but should be used with caution. If you still want the keep the original data.table, use copy first.

Usage

mutate(.data, ..., by)

transmute(.data, ..., by)

mutate_when(.data, when, ..., by)

mutate_vars(.data, .cols = NULL, .func, ..., by)

Value

A data.table

Arguments

.data

A data.table

...

Name-value pairs of expressions

by

(Optional) Mutate by what group?

when

An object which can be coerced to logical mode

.cols

Any types that can be accepted by select_dt.

.func

Function to be run within each column, should return a value or vectors with same length.

Examples

Run this code
  # Newly created variables are available immediately
  a = as.data.table(mtcars)
  copy(a) %>% mutate(cyl2 = cyl * 2)
  a

  # change forever
  a %>% mutate(cyl2 = cyl * 2)
  a

  # You can also use mutate() to remove variables and
  # modify existing variables
  a %>% mutate(
    mpg = NULL,
    disp = disp * 0.0163871 # convert to litres
  )

  a %>% transmute(cyl,one = 1)
  a


 iris[3:8,] %>%
   as.data.table() %>%
   mutate_when(Petal.Width == .2,
               one = 1,Sepal.Length=2)

 iris[3:8,] %>%
   as.data.table() %>%
   mutate_vars("Pe",scale)

Run the code above in your browser using DataLab