如何创建均值+ -sd data.frame?

时间:2017-11-23 07:09:50

标签: r aggregate mean

我希望创建(平均值±标准差)形式 下面是示例代码

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

新表组件的平均值±sd是按类型 喜欢这个..

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

请帮帮我

1 个答案:

答案 0 :(得分:1)

我们可以按'类型'分组并使用summarise_all。假设我们要添加和减去meansd并获取汇总列

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

如果需要character

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