我有一组数据,其中包含有关客户及其花费的信息,每位客户只出现一次:
customer<-c("Andy","Bobby","Oscar","Oliver","Jane","Cathy","Emma","Chris")
age<-c(25,34,20,35,23,35,34,22)
gender<-c("male","male","male","male","female","female","female","female")
moneyspent<-c(100,100,200,200,400,400,500,200)
data<-data.frame(customer=customer,age=age,gender=gender,moneyspent=moneyspent)
如果我想计算男性和女性客户平均花费的金额,我可以使用tapply:
tapply(moneyspent,gender,mean)
给出:
female male
375 150
但是,我现在想要找到性别和年龄组所花费的平均金额,而我的目标是:
Male Age 20-30 Female Age 20-30 Male Age 30-40 Female Age 30-40
150 300 150 450
我如何修改tapply代码以便它提供这些结果?
谢谢你
答案 0 :(得分:2)
您可能需要使用cut
mat <- tapply(moneyspent, list(gender, age=cut(age, breaks=c(20,30,40),
include.lowest=TRUE)), mean)
nm1 <- outer(rownames(mat), colnames(mat), FUN=paste)
setNames(c(mat), nm1)
#female [20,30] male [20,30] female (30,40] male (30,40]
# 300 150 450 150
其他选项包括
library(dplyr)
data %>%
group_by(gender, age=cut(age, breaks=c(20,30,40),
include.lowest=TRUE)) %>%
summarise(moneyspent=mean(moneyspent))
或者
library(data.table)
setDT(data)[, list(moneyspent=mean(moneyspent)),
by=list(gender, age=cut(age, breaks= c(20,30,40), include.lowest=TRUE))]
答案 1 :(得分:0)
library(plyr)
ddply(data,.(gender, age=cut(age, breaks=c(20,30,40),
include.lowest=TRUE)), summarize, moneyspent=mean(moneyspent))
也会给出相同的结果。
注意:Summari z e和Summari s e执行相同的功能。
警告:加载plyr
会掩盖dplyr
的摘要!您需要detach
plyr
,然后再使用Summarize
之类的功能。