stretch.Rd
Pivot one or more values across the columns by one or more keys
stretch(
data,
key,
value,
sep = "_"
)
A data.frame
.
A vector of quoted/unquoted columns, positions, and/or tidyselect::select_helpers
whose values will become the column name(s).
A vector of quoted/unquoted columns, positions, and/or tidyselect::select_helpers
whose values will be spread across the columns.
String to separate keys/values by in the resulting column names. Defaults to "_"
. Only used when there are more than one keys/values.
In the case of multiple value
's, the labels are always appended to the end of the resulting columns.
#Make a summary table
set.seed(123)
data <-
heart_disease %>%
dplyr::group_by(
Sex,
BloodSugar,
HeartDisease
) %>%
dplyr::summarise(
Mean = mean(Age),
SD = sd(Age),
.groups = "drop"
) %>%
dplyr::mutate(
Random =
rbinom(nrow(.), size = 1, prob = .5) %>%
factor
)
data %>%
stretch(
key = c(BloodSugar, HeartDisease),
value = c(Mean, SD, Random)
)
#> # A tibble: 2 × 13
#> Sex FALSE…¹ FALSE…² FALSE…³ FALSE…⁴ FALSE…⁵ FALSE…⁶ TRUE_…⁷ TRUE_…⁸ TRUE_…⁹
#> <fct> <dbl> <dbl> <fct> <dbl> <dbl> <fct> <dbl> <dbl> <fct>
#> 1 Female 54.0 10.4 0 59.7 3.61 1 60.3 6.65 0
#> 2 Male 50.2 8.82 1 55.8 8.56 0 54.7 6.76 1
#> # … with 3 more variables: TRUE_Yes_Mean <dbl>, TRUE_Yes_SD <dbl>,
#> # TRUE_Yes_Random <fct>, and abbreviated variable names ¹FALSE_No_Mean,
#> # ²FALSE_No_SD, ³FALSE_No_Random, ⁴FALSE_Yes_Mean, ⁵FALSE_Yes_SD,
#> # ⁶FALSE_Yes_Random, ⁷TRUE_No_Mean, ⁸TRUE_No_SD, ⁹TRUE_No_Random
data %>%
stretch(
key = where(is.factor),
value = where(is.numeric)
)
#> # A tibble: 2 × 11
#> BloodSugar Female_No…¹ Femal…² Femal…³ Femal…⁴ Male_…⁵ Male_…⁶ Male_…⁷ Male_…⁸
#> <lgl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 FALSE 54.0 10.4 59.7 3.61 50.2 8.82 55.8 8.56
#> 2 TRUE 60.3 6.65 57.2 7.81 54.7 6.76 NA NA
#> # … with 2 more variables: Male_Yes_1_Mean <dbl>, Male_Yes_1_SD <dbl>, and
#> # abbreviated variable names ¹Female_No_0_Mean, ²Female_No_0_SD,
#> # ³Female_Yes_1_Mean, ⁴Female_Yes_1_SD, ⁵Male_No_1_Mean, ⁶Male_No_1_SD,
#> # ⁷Male_Yes_0_Mean, ⁸Male_Yes_0_SD
data %>%
stretch(
key = c(where(is.factor), where(is.logical)),
value = where(is.numeric)
)
#> # A tibble: 1 × 16
#> Female_No_0_…¹ Femal…² Femal…³ Femal…⁴ Femal…⁵ Femal…⁶ Femal…⁷ Femal…⁸ Male_…⁹
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 54.0 10.4 60.3 6.65 59.7 3.61 57.2 7.81 50.2
#> # … with 7 more variables: Male_No_1_FALSE_SD <dbl>, Male_No_1_TRUE_Mean <dbl>,
#> # Male_No_1_TRUE_SD <dbl>, Male_Yes_0_FALSE_Mean <dbl>,
#> # Male_Yes_0_FALSE_SD <dbl>, Male_Yes_1_TRUE_Mean <dbl>,
#> # Male_Yes_1_TRUE_SD <dbl>, and abbreviated variable names
#> # ¹Female_No_0_FALSE_Mean, ²Female_No_0_FALSE_SD, ³Female_No_0_TRUE_Mean,
#> # ⁴Female_No_0_TRUE_SD, ⁵Female_Yes_1_FALSE_Mean, ⁶Female_Yes_1_FALSE_SD,
#> # ⁷Female_Yes_1_TRUE_Mean, ⁸Female_Yes_1_TRUE_SD, ⁹Male_No_1_FALSE_Mean