数据帧中每个组的平均值我有一个data.frame我需要计算每个组的平均值(即Month(见下文)。Name Month Rate1 Rate2Aira 1 12 23Aira 2 18 73Aira 3 19 45Ben 1 53 19Ben 2 22 87Ben 3 19 45Cat 1 22 87Cat 2 67 43Cat 3 45 32我想要的输出如下所示,其中Rate1和Rate2是团体的手段。请不要理会它的价值,我已经为这个例子编造了它。Name Rate1 Rate2Aira 23.21 12.2Ben 45.23 43.9Cat 33.22 32.2
4 回答
汪汪一只猫
TA贡献1898条经验 获得超8个赞
aggregate
d <- read.table(text='Name Month Rate1 Rate2 Aira 1 12 23 Aira 2 18 73 Aira 3 19 45 Ben 1 53 19 Ben 2 22 87 Ben 3 19 45 Cat 1 22 87 Cat 2 67 43 Cat 3 45 32', header=TRUE)aggregate(d[, 3:4], list(d$Name), mean) Group.1 Rate1 Rate21 Aira 16.33333 47.000002 Ben 31.33333 50.333333 Cat 44.66667 54.00000
d
d$Name
mean
aggregate(. ~ Name, d[-2], mean)
Qyouu
TA贡献1786条经验 获得超11个赞
或使用group_by
& summarise_at
从dplyr
一揽子:
library(dplyr)d %>% group_by(Name) %>% summarise_at(vars(-Month), funs(mean(., na.rm=TRUE)))# A tibble: 3 x 3 Name Rate1 Rate2 <fct> <dbl> <dbl>1 Aira 16.3 47.02 Ben 31.3 50.33 Cat 44.7 54.0
看见?summarise_at
用于指定要操作的变量的许多方法。这里,vars(-Month)
所有变量除 Month
.
12345678_0001
TA贡献1802条经验 获得超5个赞
data.table
library(data.table)mydt <- structure(list(Name = c("Aira", "Aira", "Aira", "Ben", "Ben", "Ben", "Cat", "Cat", "Cat"), Month = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), Rate1 = c(15.6396600443877, 2.15649279424609, 6.24692918928743, 2.37658797276116, 34.7500663272292, 3.28750138697048, 29.3265553981065, 17.9821839334431, 10.8639802575958), Rate2 = c(17.1680489538369, 5.84231656330206, 8.54330866437461, 5 .88415184986176, 3.02064294862551, 17.2053351400752, 16.9552950199166, 2.56058000170089, 15.7496228048122)), .Names = c("Name", "Month", "Rate1", "Rate2"), row.names = c(NA, -9L), class = c("data.table", "data.frame"))
colstoavg <- names(mydt)[3:4]
mydt.mean <- mydt[,lapply(.SD,mean,na.rm=TRUE),by=Name,.SDcols=colstoavg] mydt.mean Name Rate1 Rate21: Aira 8.014361 10.5178912: Ben 13.471385 8.7033773: Cat 19.390907 11.755166
- 4 回答
- 0 关注
- 820 浏览
添加回答
举报
0/150
提交
取消