rowwise_mutate: Create new data in a strictly row-wise fashion without...

View source: R/standalone-tidy-utils.R

rowwise_mutateR Documentation

Create new data in a strictly row-wise fashion without vectorisation

Description

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.

Usage

rowwise_mutate(.data, ..., .onerror = function(e, ...) NA)

Arguments

.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

Value

a dataframe the same length as input with additional or altered columns

Examples

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

terminological/ggrrr documentation built on June 15, 2024, 6:35 a.m.