View source: R/standalone-tidy-utils.R
rowwise_mutate | R Documentation |
Applies an expression to each row and assignes it to a new column. Per-row failures are handled with default values (NAs) or can be intercepted by the user with a tryCatch(...) expression. There are many other ways to do a similar thing in 'dplyr' and 'purrr' but they are all more complicated than I expect them to be.
rowwise_mutate(.data, ..., .onerror = function(e, ...) NA)
.data |
a dataframe. grouping is ingnored |
... |
a named list of expressions similar to mutate but where the expressions to be evaluated are evaluated in only in the context of the current row - and are not vectorised. This does not support [dplyr::accross] syntax. |
.onerror |
a function that is called for |
a dataframe the same length as input with additional or altered columns
# calculations are scoped only to current row. Hence max(x) == x always:
iris %>% rowwise_mutate(
widths = Sepal.Width+max(Petal.Width),
lengths = Sepal.Length+max(Petal.Length),
tmp = tibble::tibble(a=1, b=2)) %>%
dplyr::glimpse()
# This is different to standard dplyr behaviour when the additional tibble
# column is considered. standard dplyr rowwise does something unexpected:
iris %>% dplyr::rowwise() %>% dplyr::mutate(
widths = Sepal.Width+max(Petal.Width),
lengths = Sepal.Length+max(Petal.Length),
tmp = tibble::tibble(a=1, b=2)) %>%
dplyr::glimpse()
# As expressions are not vectorised we can use normal if ... else ... statements
# and errors can be handled and default values provided.
suppressWarnings(
iris %>% rowwise_mutate(
tmp = if (Petal.Width > 2.0) stop("error message: ",Petal.Width) else Petal.Width,
.onerror = function(e) -Petal.Width
) %>%
dplyr::glimpse()
)
# The default values
# are evaluated in the same context as the original expression, but only are
# defaults for all the columns so makes most sense when a default value is given
suppressWarnings(
iris %>% rowwise_mutate(
tmp = if (Petal.Width > 2.0) stop("too wide petals: ",Petal.Width) else Petal.Width,
tmp2 = if (Sepal.Width > 4) stop("too wide sepals: ",Sepal.Width) else Sepal.Width,
.onerror = function(e) Inf
) %>%
dplyr::glimpse()
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.