R/pairwise.R
pairwise.Rd
pairwise()
creates all combinations of columns and then applies function(s)
to these.
pairwise()
largely mirror dplyr::across()
in style (and is meant to be
used primarily within dplyr::mutate()
and dplyr::summarise()
).
pairwise( .cols = everything(), .fns = NULL, ..., .names = NULL, .is_commutative = FALSE )
.cols | < |
---|---|
.fns | Functions to apply to each pair of the selected columns. Possible values are:
list(difference = `-`, ratio = ~ .x / .y) The output length of a function should in most cases be 1 (in the
summarisng case) or the length of an individual input (in the mutating
case), similar to what is expected by |
... | Additional arguments for the function calls in |
.names | A glue specification that describes how to name the outputted
columns. Use Default format when When |
.is_commutative | If |
pairwise()
returns a tibble with one column for each possible pairwise combination in .cols
.
#> #>#>#> #>#>#> #>library(pwiser) library(palmerpenguins) penguins <- na.omit(penguins) # Grouped summary of correlations penguins %>% group_by(species) %>% summarise(pairwise(contains("_mm"), ~stats::cor.test(.x, .y)$p.value, .is_commutative = TRUE), n = n())#> # A tibble: 3 x 5 #> species bill_length_mm_bill~ bill_length_mm_flipp~ bill_depth_mm_flipp~ n #> <fct> <dbl> <dbl> <dbl> <int> #> 1 Adelie 1.51e- 6 4.18e- 5 1.34e- 4 146 #> 2 Chinstr~ 1.53e- 9 4.92e- 5 2.16e- 7 68 #> 3 Gentoo 7.34e-16 1.80e-16 1.40e-19 119# Building new columns penguins %>% mutate(pairwise(contains("_mm"), list(ratio = `/`, difference = `-`), .names = "features_{.fn}_{.col_x}_{.col_y}"), n = n()) %>% glimpse()#> Rows: 333 #> Columns: 21 #> $ species <fct> Adelie, Adelie, A~ #> $ island <fct> Torgersen, Torger~ #> $ bill_length_mm <dbl> 39.1, 39.5, 40.3,~ #> $ bill_depth_mm <dbl> 18.7, 17.4, 18.0,~ #> $ flipper_length_mm <int> 181, 186, 195, 19~ #> $ body_mass_g <int> 3750, 3800, 3250,~ #> $ sex <fct> male, female, fem~ #> $ year <int> 2007, 2007, 2007,~ #> $ features_ratio_bill_length_mm_bill_depth_mm <dbl> 2.090909, 2.27011~ #> $ features_difference_bill_length_mm_bill_depth_mm <dbl> 20.4, 22.1, 22.3,~ #> $ features_ratio_bill_length_mm_flipper_length_mm <dbl> 0.2160221, 0.2123~ #> $ features_difference_bill_length_mm_flipper_length_mm <dbl> -141.9, -146.5, -~ #> $ features_ratio_bill_depth_mm_bill_length_mm <dbl> 0.4782609, 0.4405~ #> $ features_difference_bill_depth_mm_bill_length_mm <dbl> -20.4, -22.1, -22~ #> $ features_ratio_bill_depth_mm_flipper_length_mm <dbl> 0.10331492, 0.093~ #> $ features_difference_bill_depth_mm_flipper_length_mm <dbl> -162.3, -168.6, -~ #> $ features_ratio_flipper_length_mm_bill_length_mm <dbl> 4.629156, 4.70886~ #> $ features_difference_flipper_length_mm_bill_length_mm <dbl> 141.9, 146.5, 154~ #> $ features_ratio_flipper_length_mm_bill_depth_mm <dbl> 9.679144, 10.6896~ #> $ features_difference_flipper_length_mm_bill_depth_mm <dbl> 162.3, 168.6, 177~ #> $ n <int> 333, 333, 333, 33~