我想在给定类别中找到数值的百分比分布,但是按第二类别分组。例如,假设我有一个包含region
,line_of_business
和sales
的数据框,我希望找到sales
的{{1}}百分比,分组按line_of_business
。
我可以使用R的内置region
和aggregate
函数执行此操作,但我很好奇是否有更短的方法可以使用merge
的{{1}} plyr
避免显式调用'ddply
的函数。
答案 0 :(得分:1)
如何创建交叉表并按比例?
total_sales <- xtabs(sales~region+line_of_business, data=df)
prop.table(total_sales, 1)
答案 1 :(得分: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