I have a dataset with quartile columns
library(dplyr)
library(glue)
set.seed(234)
df =
tibble(x1 = sample(1:100, size = 100), # simulate data
y1 = sample(1:100, size = 100),
z1 = sample(1:100, size = 100)) %>%
mutate(across(ends_with("1"), ~factor(ntile(.x, 4)), # assign to quartiles
.names = "{.col}_q"))
head(df)
#> # A tibble: 6 × 6
#> x1 y1 z1 x1_q y1_q z1_q
#> <int> <int> <int> <fct> <fct> <fct>
#> 1 97 94 9 4 4 1
#> 2 31 66 66 2 3 3
#> 3 34 43 62 2 2 3
#> 4 46 57 41 2 3 2
#> 5 98 3 38 4 1 2
#> 6 18 37 40 1 2 2
For each of these quartile columns, I would like to append the min and the max of the quartile like so:
df %>%
group_by(x1_q) %>%
mutate(x1_q = glue("Q{x1_q} ({min(x1)} - {max(x1)})")) %>%
head()
#> # A tibble: 6 × 6
#> # Groups: x1_q [3]
#> x1 y1 z1 x1_q y1_q z1_q
#> <int> <int> <int> <glue> <fct> <fct>
#> 1 97 94 9 Q4 (76 - 100) 4 1
#> 2 31 66 66 Q2 (26 - 50) 3 3
#> 3 34 43 62 Q2 (26 - 50) 2 3
#> 4 46 57 41 Q2 (26 - 50) 3 2
#> 5 98 3 38 Q4 (76 - 100) 1 2
#> 6 18 37 40 Q1 (1 - 25) 2 2
Created on 2022-04-29 by the reprex package (v2.0.1)
Is there a scalable was I can apply this group_by mutate pattern to all of my quartile columns?