Вы можете использовать aggregate/reshape
подход.
res <- reshape(aggregate(. ~ id + location + sex, data=dat, function(x)
mean(x[1:7]))[-4], varying=4:9, idvar=1:3, direction="long", sep="")
res[order(res$id), ] # just a little order
# id location sex time var
# 12.A.M.1 12 A M 1 0.23035482
# 12.A.M.2 12 A M 2 0.67700690
# 12.A.M.3 12 A M 3 0.12926876
# 12.A.M.4 12 A M 4 0.06464387
# 12.A.M.5 12 A M 5 -0.39031674
# 12.A.M.6 12 A M 6 -0.21768911
# 234.A.M.1 234 A M 1 0.17089758
# 234.A.M.2 234 A M 2 -0.09195034
# 234.A.M.3 234 A M 3 0.40042572
# 234.A.M.4 234 A M 4 0.23404603
# 234.A.M.5 234 A M 5 0.08176435
# 234.A.M.6 234 A M 6 0.02859807
Или используя by
do.call(rbind, by(dat, dat$id, function(x) {
cbind(x[1:6, 1:3], var=names(x[5:10]), mn=colMeans(x[1:7, 5:10]))
}))
# id location sex var mn
# 12.1 12 A M var1 0.23035482
# 12.3 12 A M var2 0.67700690
# 12.5 12 A M var3 0.12926876
# 12.7 12 A M var4 0.06464387
# 12.9 12 A M var5 -0.39031674
# 12.11 12 A M var6 -0.21768911
# 234.2 234 A M var1 0.17089758
# 234.4 234 A M var2 -0.09195034
# 234.6 234 A M var3 0.40042572
# 234.8 234 A M var4 0.23404603
# 234.10 234 A M var5 0.08176435
# 234.12 234 A M var6 0.02859807
Данные:
set.seed(42)
dat <- expand.grid(id=c(12, 234), location="A", sex="M", time=(1:20)/10)
dat <- cbind(dat, matrix(rnorm(240), 40, 6, dimnames=list(NULL, paste0("var", 1:6))))
dat <- dat[order(dat$id), ]