mutate | R Documentation |
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.
mutate(.data, ..., by)
transmute(.data, ..., by)
mutate_when(.data, when, ..., by)
mutate_vars(.data, .cols = NULL, .func, ..., by)
.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 |
.func |
Function to be run within each column, should return a value or vectors with same length. |
A data.table
# 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)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.