这是我的数据的一个可重复的小示例:
> mydata <- structure(list(subject = c(1, 1, 1, 2, 2, 2), time = c(0, 1, 2, 0, 1, 2), measure = c(10, 12, 8, 7, 0, 0)), .Names = c("subject", "time", "measure"), row.names = c(NA, -6L), class = "data.frame")
> mydata
subject time measure
1 0 10
1 1 12
1 2 8
2 0 7
2 1 0
2 2 0
我想生成一个新变量,其中包含该measure
特定主题的平均值,因此:
subject time measure mn_measure
1 0 10 10
1 1 12 10
1 2 8 10
2 0 7 2.333
2 1 0 2.333
2 2 0 2.333
有没有一种简单的方法可以做到这一点,除了以编程方式循环遍历所有记录或首先重塑为宽格式?