【问题标题】:How to calculate top rows from a large data set如何从大型数据集中计算顶行
【发布时间】:2015-01-24 14:39:38
【问题描述】:

我有一个数据集,其中包含以下列:flavor、flavorid 和 unitSoled。

Flavor Flavorid unitsoled
beans  350       6
creamy 460       2
.
.
.

我想找出前十种口味,然后计算每种口味的市场份额。我的逻辑是每种口味的市场份额=特定口味的销售单位除以销售的总单位。

我该如何实现。对于输出,我只想要两个 col Flavorid 和相应的市场份额。我需要先在某个表中保存前十种口味吗?

【问题讨论】:

  • aggregate(unitsoled ~ Flavorid, df, sum) -> 这部分是按 id 计算单位鞋底的总和,之后我想显示前 10 种口味,然后计算前 10 种口味中的每一种的市场份额风味使用公式:特定风味的销售单位除以销售的总单位。 head(df2, 10)->> 这没有显示正确的结果。
  • 看看Lyzander的详细解答

标签: r aggregate subset


【解决方案1】:

一种方法是使用dplyr 包:

一个示例数据集:

flavor    <- rep(letters[1:15],each=5)
flavorid  <- rep(1:15,each=5)
unitsold  <- 1:75
df <- data.frame(flavor,flavorid,unitsold)

> df
   flavor flavorid unitsold
1       a        1        1
2       a        1        2
3       a        1        3
4       a        1        4
5       a        1        5
6       b        2        6
7       b        2        7
8       b        2        8
9       b        2        9
...
...

解决方案:

library(dplyr)
df %>%
  select(flavorid,unitsold) %>%             #select the columns you want
  group_by(flavorid) %>%                    #group by flavorid
  summarise(total=sum(unitsold)) %>%        #sum the total units sold per id
  mutate(marketshare=total/sum(total)) %>%  #calculate the market share per id
  arrange( desc(marketshare)) %>%           #order by marketshare descending
  head(10)                                  #pick the 10 first
  #and you can add another select(flavorid,marketshare) if you only want those two

输出:

Source: local data frame [10 x 3]

   flavorid total marketshare
1        15   365  0.12807018
2        14   340  0.11929825
3        13   315  0.11052632
4        12   290  0.10175439
5        11   265  0.09298246
6        10   240  0.08421053
7         9   215  0.07543860
8         8   190  0.06666667
9         7   165  0.05789474
10        6   140  0.04912281

【讨论】:

  • 您不需要提前计算 allmarket,它可以在 mutate 调用中以 mutate(marketshare = total/sum(total) 完成。标题行也可以是head(10) - 不需要点。
  • @JesseRaab 感谢您的评论杰西。两者都是有效点。我做了更改。
  • 谢谢大家。我是新手,所以想知道解决方案中的 %>% 是什么?
  • 它被称为管道,它来自magrittr包。在上面的 dplyr package 中也用到了它。它将%&gt;% 的左侧发送到它的右侧。例如df %&gt;% select(flavorid,unitsold) 将data.frame df 发送到函数select,该函数选择列flavorid 和untisold。建议你看一下dplyrhere的介绍。很容易理解并解释上述所有功能。而且很短。
  • 我还有一个基本问题:
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 2017-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
相关资源
最近更新 更多