xtabs()
一起使用如下aggregate()
:
df <- data.frame(id = c(1,1,1,1,1,2,2,2,2),
spent = c(10,10,20,10,10,5,5,5,20),
period = c("f","c","c","v","v","f","c","c","v"),
mean.spent = c(10,15,15,10,10,5,5,5,20))
xtabs(spent ~ id + period, aggregate(spent ~ id + period, df, mean))
# period
# id c f v
# 1 15 10 10
# 2 5 5 20
aggregate
计算每组的平均值(按“id”和“周期”分组),并将xtabs
转换为这种更广泛的格式。
以下是如何将其变为data.frame
:
temp1 <- xtabs(spent ~ id + period,
aggregate(spent ~ id + period, df, mean))
data.frame(id = dimnames(temp1)$id, as.data.frame.matrix(temp1))
# id c f v
# 1 1 15 10 10
# 2 2 5 5 20
更新:更直接的方法
我总是忘记tapply
,但是这个例子在方便的时候是一个很好的选择。
tapply(df$spent, list(df$id, df$period), mean)
# c f v
# 1 15 10 10
# 2 5 5 20