pivot_helper.Rd
A function that pretty much let's you do anything in the tidypivot space, is carefully crafted, and is adapted to make the other functions easy to use
pivot_helper( data, rows = NULL, cols = NULL, value = NULL, wt = NULL, within = NULL, fun = NULL, pivot = T, wrap = F )
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. |
---|---|
rows | a character vector of items |
cols | a character vector of items |
pivot | logical: should wide table be returned - col categories as columns (TRUE), or left long and tidy (FALSE)? |
tidy_titanic %>% pivot_helper(rows = sex, cols = survived, fun = length) # pivot_count#> # A tibble: 2 × 3 #> sex No Yes #> <fct> <int> <int> #> 1 Male 1364 367 #> 2 Female 126 344flat_titanic %>% pivot_helper(rows = sex, value = freq, fun = mean) # pivot_calc#> # A tibble: 2 × 2 #> sex value #> <fct> <dbl> #> 1 Male 108. #> 2 Female 29.4flat_titanic %>% pivot_helper(rows = sex, value = freq, fun = sum) # pivot_count (weighted sum)#> # A tibble: 2 × 2 #> sex value #> <fct> <dbl> #> 1 Male 1731 #> 2 Female 470nar <- function(x) return(NA) flat_titanic %>% pivot_helper(rows = sex, cols = survived, fun = nar); #pivot_null#> # A tibble: 2 × 3 #> sex No Yes #> <fct> <lgl> <lgl> #> 1 Male NA NA #> 2 Female NA NAsample1 <- function(x) sample(x, 1) flat_titanic %>% pivot_helper(rows = sex, cols = survived, fun = sample1, value = freq); #pivot_sample1#> # A tibble: 2 × 3 #> sex No Yes #> <fct> <dbl> <dbl> #> 1 Male 0 192 #> 2 Female 3 1samplen <- function(x, n) paste(sample(x, 5, replace = F), collapse = ", ") flat_titanic %>% pivot_helper(rows = sex, cols = survived, fun = samplen, value = freq); #pivot_samplen#> # A tibble: 2 × 3 #> sex No Yes #> <fct> <chr> <chr> #> 1 Male 0, 0, 670, 387, 0 14, 192, 57, 13, 0 #> 2 Female 0, 13, 0, 3, 89 1, 140, 20, 76, 13paste_collapse <- function(x) paste (x, collapse = ", ") flat_titanic %>% pivot_helper(rows = sex, fun = paste_collapse, value = freq) #pivot_list#> # A tibble: 2 × 2 #> sex value #> <fct> <chr> #> 1 Male 0, 0, 35, 0, 118, 154, 387, 670, 5, 11, 13, 0, 57, 14, 75, 192 #> 2 Female 0, 0, 17, 0, 4, 13, 89, 3, 1, 13, 14, 0, 140, 80, 76, 20