Search code examples
raggregatemean

How to create mean+-sd data.frame?


I hope create (mean ± sd ) form.
below is example code

a=c("type","A","B","C")
b=c("a","a","b","b")
c=c(22, 32, 23, 20)
d=c(12,25,23,30)
e=c(15,17,23,35)
f=data.frame(b,c,d,e)
colnames(f)=a

new table component mean ± sd is by type.
like this ..

type A B C 
a  mean ± sd .. mean ± sd 
b  mean ± sd .. mean ± sd 

please help me


Solution

  • We can group by 'type' and use summarise_all. Assuming that we want to add and subtract the mean and sd and get the summarised columns

    library(dplyr)
    f %>%
       group_by(type) %>% 
       summarise_all(funs(mean(.) + round(sd(.), 2), mean(.)- round(sd(.), 2)))
    # A tibble: 2 x 7
    #    type `A_+` `B_+` `C_+` `A_-` `B_-` `C_-`
    #   <fctr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
    #1      a 34.07 27.69 17.41 19.93  9.31 14.59
    #2      b 23.62 31.45 37.49 19.38 21.55 20.51
    

    If this is needed as a character class

    f %>%
      group_by(type) %>%
      summarise_all(funs(paste(mean(.), round(sd(.), 2), sep=" ± ")))
    # A tibble: 2 x 4
    #    type           A           B         C
    #   <fctr>       <chr>       <chr>     <chr>
    #1      a   27 ± 7.07 18.5 ± 9.19 16 ± 1.41
    #2      b 21.5 ± 2.12 26.5 ± 4.95 29 ± 8.49