Reputation: 19
Hi guys is it possible to get mean and standard deviation into a single column?
for example if i had the following code;
data %>%
select(age, gender) %>%
group_by(gender) %>%
summarise(mean.age = mean(age), sd.age = sd(age)
this would display a tibble with mean age and standard deviation for each gender as 2 separate column.
how do i get this to display as one column so the format is like "age = 18 ± 2"?
Upvotes: 0
Views: 545
Reputation: 887311
We can use glue
library(dplyr)
library(glue)
data %>%
group_by(gender) %>%
summarise(age = glue('{round(mean(age), 2)} ± {round(sd(age), 2)}')
A reproducible example with mtcars
mtcars %>%
group_by(cyl) %>%
summarise(age = glue('{round(mean(mpg), 2)} ± {round(sd(mpg), 2)}'))
# A tibble: 3 x 2
cyl age
<dbl> <glue>
1 4 26.66 ± 4.51
2 6 19.74 ± 1.45
3 8 15.1 ± 2.56
Upvotes: 0
Reputation: 389055
You can paste the two values together.
library(dplyr)
data %>%
group_by(gender) %>%
summarise(age = paste(round(mean(age),2), round(sd(age),2) sep = ' ± '))
For eg with mtcars
data -
mtcars %>%
group_by(cyl) %>%
summarise(age = paste(round(mean(mpg), 2), round(sd(mpg), 2), sep = ' ± '))
# cyl age
# <dbl> <chr>
#1 4 26.66 ± 4.51
#2 6 19.74 ± 1.45
#3 8 15.1 ± 2.56
Upvotes: 2