mutate_pmap: Use 'pmap' to create a new column in a data.frame

View source: R/mutate_pmap.r

mutate_pmapR Documentation

Use pmap to create a new column in a data.frame

Description

Sometimes you want to use mutate to create a new column in a data.frame, but that function doesn't work with vectors. One workaround is to use a rowwise() %>% mutate(), however that is quite slow. This function lets you use the speed of pmap in a mutate-like syntax (and returns the original data.frame with a new column, instead of just a list). This works best if the column names of .data match the arguments expected by .f.

Usage

mutate_pmap(.data, col_name, .f, ...)

Arguments

.data

A data frame, data frame extension (e.g. a tibble), or a lazy data frame (e.g. from dbplyr or dtplyr). See Methods, below, for more details.

col_name

(unquoted character) the name of the new column you want to add

.f

A function, specified in one of the following ways:

  • A named function.

  • An anonymous function, e.g. ⁠\(x, y, z) x + y / z⁠ or function(x, y, z) x + y / z

  • A formula, e.g. ~ ..1 + ..2 / ..3. This syntax is not recommended as you can only refer to arguments by position.

...

Additional arguments passed on to the mapped function.

We now generally recommend against using ... to pass additional (constant) arguments to .f. Instead use a shorthand anonymous function:

# Instead of
x |> map(f, 1, 2, collapse = ",")
# do:
x |> map(\(x) f(x, 1, 2, collapse = ","))

This makes it easier to understand which arguments belong to which function and will tend to yield better error messages.

Value

.data with a new column named after col_name.

Examples

## Not run: 

# Create a column of charts:

# Create a custom plotting function
plot_starwars <- function(data) {
  ggplot2::qplot(x = mass, y = height, data = data)
}

# Make a tibble with the starwars data in twice
tibble::tibble(data = list(
  dplyr::starwars,
  dplyr::starwars
)) %>%
  mutate_pmap(
    col_name = plot,
    .f = plot_starwars
  )

## End(Not run)

baslat/sak documentation built on April 14, 2025, 4:14 p.m.