mutate: Create or transform variables

View source: R/mutate.R

mutateR Documentation

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)

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.

Value

A data.table

Examples

  # 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)


tidyft documentation built on Jan. 9, 2023, 1:27 a.m.