library(presenter)
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, unionTranspose a tibble of summary statistics in tidy format. Convenient
function for transposing the output of dplyr”s group_by and
summarize operation.
Transpose a 1 row numerical summary:
wide format
iris %>%
summarize(across(where(is.numeric), mean), .groups = "drop") -> sumr0
sumr0
#> Sepal.Length Sepal.Width Petal.Length Petal.Width
#> 1 5.843333 3.057333 3.758 1.199333long format
sumr0 %>%
pivot_summary()
#> # A tibble: 4 × 2
#> column V1
#> <chr> <dbl>
#> 1 Sepal.Length 5.84
#> 2 Sepal.Width 3.06
#> 3 Petal.Length 3.76
#> 4 Petal.Width 1.20A grouped summary can be transposed by providing the name of the group column.
wide format
iris %>%
group_by(Species) %>%
summarize(across(where(is.numeric), mean), .groups = "drop") -> sumr1
sumr1
#> # A tibble: 3 × 5
#> Species Sepal.Length Sepal.Width Petal.Length Petal.Width
#> <fct> <dbl> <dbl> <dbl> <dbl>
#> 1 setosa 5.01 3.43 1.46 0.246
#> 2 versicolor 5.94 2.77 4.26 1.33
#> 3 virginica 6.59 2.97 5.55 2.03long format
sumr1 %>%
pivot_summary(Species)
#> # A tibble: 4 × 4
#> column setosa versicolor virginica
#> <chr> <dbl> <dbl> <dbl>
#> 1 Sepal.Length 5.01 5.94 6.59
#> 2 Sepal.Width 3.43 2.77 2.97
#> 3 Petal.Length 1.46 4.26 5.55
#> 4 Petal.Width 0.246 1.33 2.03Supports transposing numerical summaries with multiple groups using tidyselect.
long format
iris %>%
mutate(Species1 = sample(Species)) %>%
group_by(Species, Species1) %>%
summarize(across(where(is.numeric), mean), .groups = "drop") -> sumr2
sumr2
#> # A tibble: 9 × 6
#> Species Species1 Sepal.Length Sepal.Width Petal.Length Petal.Width
#> <fct> <fct> <dbl> <dbl> <dbl> <dbl>
#> 1 setosa setosa 5.06 3.42 1.46 0.238
#> 2 setosa versicolor 5.04 3.47 1.49 0.269
#> 3 setosa virginica 4.88 3.38 1.44 0.231
#> 4 versicolor setosa 6.08 2.83 4.43 1.4
#> 5 versicolor versicolor 5.79 2.74 4.04 1.28
#> 6 versicolor virginica 5.91 2.74 4.26 1.29
#> 7 virginica setosa 6.36 2.8 5.35 1.96
#> 8 virginica versicolor 6.54 3.04 5.59 2.08
#> 9 virginica virginica 6.77 3.01 5.63 2.01Group names are concatenated and pivoted.
wide format
sumr2 %>%
pivot_summary(matches("Spec"))
#> # A tibble: 4 × 10
#> column setosa_setosa setosa_versicolor setosa_virginica versicolor_setosa
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 Sepal.Leng… 5.06 5.04 4.88 6.08
#> 2 Sepal.Width 3.42 3.47 3.38 2.83
#> 3 Petal.Leng… 1.46 1.49 1.44 4.43
#> 4 Petal.Width 0.238 0.269 0.231 1.4
#> # ℹ 5 more variables: versicolor_versicolor <dbl>, versicolor_virginica <dbl>,
#> # virginica_setosa <dbl>, virginica_versicolor <dbl>,
#> # virginica_virginica <dbl>