2

我有以下数据框:

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

你能帮我做这件事吗?

4

1 回答 1

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计算每组的平均值(按“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
于 2012-12-28T06:47:07.740 回答