为每个类和每个ID聚合一个变量的值

时间:2012-12-28 06:41:21

标签: r aggregation

我有以下数据框:

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)
df <- data.frame(id,spent,period,mean.spent)

我想要的是聚合每个时期每个Id的平均花费如下:

id  f  c  v    
1   10 15 10
2   5  5  20

你能帮我做一下吗?

1 个答案:

答案 0 :(得分:6)

使用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计算每组的平均值(按&#34; id&#34;&#34;句点&#34;分组),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