充实@Roman Lustrik的建议,从而R
为简单起见保持基础:
df1 <- data.frame(
Category=c(1,2,3,1,3,2),
Price= c(10,5,20,25,5,15)
)
aggregate(df1,by=list(df1[,"Category"]),FUN=mean)
给出:
Group.1 Category Price
1 1 1 17.5
2 2 2 10.0
3 3 3 12.5
或者
tapply(df1[,"Price"], df1[,"Category"], mean)
给出:
1 2 3
17.5 10.0 12.5
(请注意df1[,"Price"]==df1$Price
,可以使用任何一种样式)。就个人而言,我更喜欢输出,aggregate()
而且速度更快,尽管在小型数据集上这是相当学术的:
require(microbenchmark)
microbenchmark( aggregate(df1,by=list(df1[,"Category"]),FUN=mean) )
microbenchmark( tapply(df1[,"Price"], df1[,"Category"], mean) )
给出(为清楚起见而简化):
min lq median uq max
2.233209 2.268719 2.311002 2.362932 4.018134
771.361 792.0915 807.2805 829.2435 1201.581
最后,如果您希望输出与问题中的示例完全相同:
a1 <- aggregate(df1,by=list(df1[,"Category"]),FUN=mean )
a1 <- a1[,-1] # remove 1st column
a1[,2] <- format(a1[,2],nsmall=2) # give 2 decimal places
colnames(a1)[2] <- "AveragePrice" # assign name to 2nd column
给出:
Category AveragePrice
1 1 17.50
2 2 10.00
3 3 12.50