Skip to content

Instantly share code, notes, and snippets.

@romainfrancois
Created November 25, 2018 21:03
Show Gist options
  • Save romainfrancois/abcbcd1ad15e7a58416843f247c01810 to your computer and use it in GitHub Desktop.
Save romainfrancois/abcbcd1ad15e7a58416843f247c01810 to your computer and use it in GitHub Desktop.
# devtools::install_github("romainfrancois/zap")
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(zap)
library(purrr)
starwars <- head(starwars)
# wap is like pmap, but it makes it easier to refer to the
# columns by their name
starwars %>%
wap(~ length(films))
#> [[1]]
#> [1] 5
#>
#> [[2]]
#> [1] 6
#>
#> [[3]]
#> [1] 7
#>
#> [[4]]
#> [1] 4
#>
#> [[5]]
#> [1] 5
#>
#> [[6]]
#> [1] 3
# creates a list of length 1 integer vectors
starwars %>%
wap_int(~ length(films))
#> [1] 5 6 7 4 5 3
# instead of e.g.
starwars %>%
pull(films) %>%
map_int(~ length(.x))
#> [1] 5 6 7 4 5 3
starwars %>%
zap_int(n = ~ length(films)) %>%
zap_dfr(x = ~ data.frame(vehicles = length(vehicles), starships = length(starships))) %>%
select(1:2, n, x)
#> # A tibble: 6 x 4
#> name height n x$vehicles $starships
#> <chr> <int> <int> <int> <int>
#> 1 Luke Skywalker 172 5 2 2
#> 2 C-3PO 167 6 0 0
#> 3 R2-D2 96 7 0 0
#> 4 Darth Vader 202 4 0 1
#> 5 Leia Organa 150 5 1 0
#> 6 Owen Lars 178 3 0 0
# instead of something like this
# (:scream: dplyr::mutate does not yet handle returning data frames from mutate)
starwars %>%
mutate(n = map_int(films, length)) %>%
tibble::add_column(x = pmap_dfr(
list(.$vehicles, .$starships),
~data.frame(vehicles = length(.x), starships = length(.y))
)) %>%
select(1:2, n, x)
#> # A tibble: 6 x 4
#> name height n x$vehicles $starships
#> <chr> <int> <int> <int> <int>
#> 1 Luke Skywalker 172 5 2 2
#> 2 C-3PO 167 6 0 0
#> 3 R2-D2 96 7 0 0
#> 4 Darth Vader 202 4 0 1
#> 5 Leia Organa 150 5 1 0
#> 6 Owen Lars 178 3 0 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment