3 回答
TA贡献1824条经验 获得超6个赞
使用base R函数ave(),尽管其名称令人困惑,它仍可以计算各种统计信息,包括mean:
within(mydata, mean<-ave(measure, subject, FUN=mean))
subject time measure mean
1 1 0 10 10.000000
2 1 1 12 10.000000
3 1 2 8 10.000000
4 2 0 7 2.333333
5 2 1 0 2.333333
6 2 2 0 2.333333
请注意,我within只是为了缩短代码而使用。这是没有的等效项within():
mydata$mean <- ave(mydata$measure, mydata$subject, FUN=mean)
mydata
subject time measure mean
1 1 0 10 10.000000
2 1 1 12 10.000000
3 1 2 8 10.000000
4 2 0 7 2.333333
5 2 1 0 2.333333
6 2 2 0 2.333333
TA贡献1875条经验 获得超3个赞
或者与data.table包:
require(data.table)
dt <- data.table(mydata, key = "subject")
dt[, mn_measure := mean(measure), by = subject]
# subject time measure mn_measure
# 1: 1 0 10 10.000000
# 2: 1 1 12 10.000000
# 3: 1 2 8 10.000000
# 4: 2 0 7 2.333333
# 5: 2 1 0 2.333333
# 6: 2 2 0 2.333333
- 3 回答
- 0 关注
- 506 浏览
添加回答
举报