rap: Map over columns of a data frame simultaneously

Description Usage Arguments Value Examples

View source: R/rap.R

Description

Map over columns of a data frame simultaneously

Usage

1
2
3
4
5
wap(.tbl, .f)

lap(.tbl, .f)

rap(.tbl, ...)

Arguments

.tbl

A data frame

.f

a single formula

...

formulas

The rhs of each formula uses columns of .tbl, and each stands for a single observation.

The lhs of each formula indicates the type, in the vctrs::vec_c() sense.

  • empty or list(): no check is performed on the results of the rhs expression and a list is returned.

  • data.frame(): to indicate that the rhs should evaluate to a data frame of 1 row. The data frames don't need to be of a specific types and are are combined with vctrs::vec_rbind().

  • A data frame of a specific type, e.g. data.frame(x = integer(), y = double()) The rhs should evaluate to a data frame of that type with 1 row.

  • Any other ptype that makes sense for vctrs::vec_c(). Each result must validate vctrs::vec_size(.) == 1L and are combined with vctrs::vec_c(!!!, .ptype = .ptype)

In rap() if the formula is named, the result becomes a new column of the tbl, otherwise the formula is only used for side effects.

Value

Examples

 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
library(purrr)
library(dplyr)
library(tibble)

tbl <- tibble(cyl_threshold = c(4, 6, 8), mpg_threshold = c(30, 25, 20))

# ----- wap
# returns a list of 3 elements
tbl %>%
  wap(       ~ filter(mtcars, cyl == cyl_threshold, mpg < mpg_threshold))

# same, i.e. list() is equivalent to empty
tbl %>%
  wap(list() ~ filter(mtcars, cyl == cyl_threshold, mpg < mpg_threshold))

# can specify the output type with the formula lhs
tbl %>%
  wap(integer() ~ nrow(filter(mtcars, cyl == cyl_threshold, mpg < mpg_threshold)))

# to make data frames
starwars %>%
  wap(data.frame() ~ data.frame(species = length(species), films = length(films)))

# ----- rap: add columns
tbl %>%
  rap(
     x =           ~ filter(mtcars, cyl == cyl_threshold, mpg < mpg_threshold),
     n = integer() ~ nrow(x)
  )

# rap is especially useful for iterating over multiple models
starwars %>%
  group_nest(gender) %>%
  rap(
    model =          ~ lm(height ~ mass + birth_year, data = data),
    perf  = double() ~ summary(model)$adj.r.squared
  )

romainfrancois/rap documentation built on Dec. 11, 2018, 1:34 a.m.