Advertisements
I’m new. I need to produce a tibble where each variable grouped by a factor and described by mean and standard deviation separated by "±".
Let’s use the iris dataset.
iris %>%
group_by(Species) %>%
summarise(across(everything(), list(Mean=mean,dev.st=sd))) %>%
pivot_longer(cols = -Species, names_to = c(".value", "variable"), names_sep = "_")
How can I continue?
Thank you in advance
>Solution :
You could use the more updated dplyr::reframe
(which replaces dplyr::summarize
) and add this combined summary statistic (comb
) to your list of functions:
library(dplyr)
library(tidyr)
iris %>%
group_by(Species) %>%
reframe(across(everything(),
list(Mean = ~ as.character(mean(.x)),
dev.sd = ~ as.character(sd(.x)),
comb = ~ paste(mean(.x), sd(.x), sep = " ± ")))) %>%
pivot_longer(cols = -Species, names_to = c(".value", "variable"),
names_sep = "_")
# (from comment) if you only wanted the combined column and want
# them at two significant digits, you could adjust:
iris %>%
group_by(Species) %>%
reframe(across(everything(),
list(comb = ~ paste(sprintf("%.2f", mean(.x)),
sprintf("%.2f", sd(.x)), sep = " ± ")))) %>%
pivot_longer(cols = -Species, names_to = c(".value", "variable"),
names_sep = "_")
#' In this case you get the exact same thing if you replace `reframe` with
#' `summarize`, but the latter is being replaced by `reframe`
#' by `dplyr` moving forward
Note to combine with the pivot_longer
, all elements need to be in the same class, so converted them to character. If you keep it wide, you dont have to add the as.character()
bit in the summary stats.
Output
Species variable Sepal.Length Sepal.Width Petal.Length Petal.Width
<fct> <chr> <chr> <chr> <chr> <chr>
1 setosa Mean 5.006 3.428 1.462 0.246
2 setosa dev.sd 0.352489687213451 0.379064369096289 0.173663996480184 0.105385589380046
3 setosa comb 5.006 ± 0.352489687213451 3.428 ± 0.379064369096289 1.462 ± 0.173663996480184 0.246 ± 0.105385589380046
4 versicolor Mean 5.936 2.77 4.26 1.326
5 versicolor dev.sd 0.516171147063863 0.313798323378411 0.469910977239958 0.197752680004544
6 versicolor comb 5.936 ± 0.516171147063863 2.77 ± 0.313798323378411 4.26 ± 0.469910977239958 1.326 ± 0.197752680004544
7 virginica Mean 6.588 2.974 5.552 2.026
8 virginica dev.sd 0.635879593274432 0.322496638172637 0.551894695663983 0.274650055636667
9 virginica comb 6.588 ± 0.635879593274432 2.974 ± 0.322496638172637 5.552 ± 0.551894695663983 2.026 ± 0.274650055636667