[英]Summarising data using tidyr/dplyr functions
以下是我的数据框:
Species Type Contents (kg)
1 T f 0.0710000
2 T f 0.1100000
3 W f 0.0200000
4 W f 0.0200000
5 S f 0.2100000
6 S f 0.2800000
7 T w 1.1400000
8 T w 0.6000000
9 W w 0.5600000
10 W w 0.5600000
11 S w 1.9800000
12 S w 3.1200000
使用dplyr函数,我得到了type f
的均值和方差,但我也想按species
对结果进行划分,并且想知道如何使用tidyr / dplyr函数来做到这一点。
这就是我用来查找上述type f
的均值和方差的方法。
summarise(group_by(Item,Type[2]),Mean = mean(Item$Contents (kg)),Variance = var(Item$Contents (kg)))
与dplyr
相对简单,只需调用mutate
df <- read.table(text =
" Row Species Type Contents(kg)
1 T f 0.0710000
2 T f 0.1100000
3 W f 0.0200000
4 W f 0.0200000
5 S f 0.2100000
6 S f 0.2800000
7 T w 1.1400000
8 T w 0.6000000
9 W w 0.5600000
10 W w 0.5600000
11 S w 1.9800000
12 S w 3.1200000",
header = TRUE, stringsAsFactors = FALSE)
library(dplyr)
df %>%
group_by(Type, Species) %>%
mutate(meanByTypeandSpecies = mean(Contents.kg.))
结果:
请尝试使用管道实用程序并进行汇总,以按组获取摘要统计信息:
Item %>%
group_by(Species, Type) %>%
summarise(
mean = mean(Contents.kg.),
variance = var(Contents.kg.)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.