Description Usage Arguments Value Useful functions available in calculations of variables Scoped mutation and transmutation Tidy data See Also Examples
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.
1 2 3 |
.data |
A tbl. All main verbs are S3 generics and provide methods
for |
... |
Name-value pairs of expressions, each with length 1 or the same
length as the number of rows in the group (if using The arguments in |
An object of the same class as .data.
+, -, log(), etc., for their usual mathematical meanings
lead(), lag()
dense_rank(), min_rank(), percent_rank(), row_number(),
cume_dist(), ntile()
cumsum(), cummean(), cummin(), cummax(), cumany(), cumall()
na_if(), coalesce()
if_else(), recode(), case_when()
The three scoped variants of mutate() (mutate_all(),
mutate_if() and mutate_at()) and the three variants of
transmute() (transmute_all(), transmute_if(),
transmute_at()) make it easy to apply a transformation to a
selection of variables.
When applied to a data frame, row names are silently dropped. To preserve,
convert to an explicit variable with tibble::rownames_to_column().
Other single table verbs: arrange,
filter, select,
slice, summarise
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | # 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))
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.