按销售和年来计算顶级产品
我有几年和副产品的销售数据,可以说是这样的:
Year <- c(2010,2010,2010,2010,2010,2011,2011,2011,2011,2011,2012,2012,2012,2012,2012)
Model <- c("a","b","c","d","e","a","b","c","d","e","a","b","c","d","e")
Sale <- c("30","45","23","33","24","11","56","19","45","56","33","32","89","33","12")
df <- data.frame(Year, Model, Sale)
数年的产品:
a = 30+11+33 = 74 B = 45+56+32 = 133 C = 23+19+89 = 131 D = 33+45+33 = 111 E = 12+56+24 = 92
根据这三年内的总销售额进行排名:
1 2 3 4 5
b c d e a
我希望按年来确定前2个产品(根据这3年内的总销售额)的代码,并将所有其余产品汇总为“其他”类别。因此,输出应该是这样:
年度销售 2010 B 45 2010 C 23 2010其他30+33+24 = 92 2011 B 56 2011 C 19 2011其他11+45+56 = 112 2012 B 32 2012 C 89 2012其他33+33+12 = 78
I have the data about sales by years and by-products, let's say like this:
Year <- c(2010,2010,2010,2010,2010,2011,2011,2011,2011,2011,2012,2012,2012,2012,2012)
Model <- c("a","b","c","d","e","a","b","c","d","e","a","b","c","d","e")
Sale <- c("30","45","23","33","24","11","56","19","45","56","33","32","89","33","12")
df <- data.frame(Year, Model, Sale)
product by years:
a= 30+11+33 = 74 b= 45+56+32 = 133 c= 23+19+89 = 131 d= 33+45+33 = 111 e= 12+56+24 = 92
Ranking by according to total sales within these 3 years:
1 2 3 4 5
b c d e a
I want the code which identifies the TOP 2 products (according to total sales within these 3 years) by years and summarises all the rest products as category "other". So the output should be like this:
year Model Sale 2010 b 45 2010 c 23 2010 other 30+33+24=92 2011 b 56 2011 c 19 2011 other 11+45+56=112 2012 b 32 2012 c 89 2012 other 33+33+12= 78
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个 tidyverse 解决方案。您的
销售
数据似乎存储为字符,这意味着我们必须在求和之前使用as.numeric
。以上解决方案通过匹配
sale
中的值来创建“其他”类别。如果这些值具有小数位置,这可能会导致问题(请参见这个问题)。取而代之的是,我们可以使用两步过程来按名称识别前两个模型,并使用它来为总数据创建分组:A tidyverse solution. Your
Sale
data appear to be stored as character, which means we'll have to useas.numeric
before summing them.The above solution creates the "other" category by matching on the values in
Sale
. This could cause problems if those values have decimal places (see this question). Instead, we could use a two-step process to identify the top two Models by name, and use this to create the groupings for the total data: