我想找到给定类别中数值的百分比分布,但按第二个类别分组。例如,假设我有一个带有region
、line_of_business
和的数据框sales
,并且我想找到sales
按line_of_business
分组的百分比region
。
我可以使用 R 的内置函数aggregate
和merge
函数来做到这一点,但我很好奇是否有更短的方法来使用plyr
''ddply
函数来避免显式调用merge
.
如何创建交叉表并获取比例?
total_sales <- xtabs(sales~region+line_of_business, data=df)
prop.table(total_sales, 1)
这是使用 plyr 的一种方法:
library(plyr)
library(reshape2)
# Create fake data
sales = rnorm(1000,10000,1000)
line_of_business = sample(c("Sporting Goods", "Computers", "Books"),
1000, replace=TRUE)
region = sample(c("East","West","North","South"), 1000, replace=TRUE)
dat = data.frame(sales, line_of_business, region)
# Sales by region by line_of_business
dat_summary = ddply(dat, .(region, line_of_business), summarise,
tot.sales=sum(sales))
# Add percentage by line_of_business, within each region
dat_summary = ddply(dat_summary, .(region), transform,
pct=round(tot.sales/sum(tot.sales)*100,2))
# Reshape, if desired
dat_summary_m = melt(dat_summary, id.var=c("region","line_of_business"))
dat_summary_w = dcast(dat_summary_m, line_of_business ~ region + variable,
value.var='value',
fun.aggregate=sum)
这是最终结果:
> dat_summary_w
line_of_business East_tot.sales East_pct North_tot.sales North_pct South_tot.sales South_pct
1 Books 852688.3 31.97 736748.4 33.2 895986.6 35.70
2 Computers 776864.3 29.13 794480.4 35.8 933407.9 37.19
3 Sporting Goods 1037619.8 38.90 687877.6 31.0 680199.1 27.10
West_tot.sales West_pct
1 707540.9 27.28
2 951677.9 36.70
3 933987.7 36.02