首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R中的数据汇总

R中的数据汇总
EN

Stack Overflow用户
提问于 2017-05-25 19:35:34
回答 2查看 697关注 0票数 2

我有一个数据集,每周按出口销售各种产品。以下是数据的样子:

代码语言:javascript
复制
Store ID    Week ID Item Code   Sales in $
253422  191 41130   2.95
272568  188 41130   2.95
272568  188 41160   2.95
272568  189 41130   2.95
272568  189 41160   2.95
272568  190 41160   2.95
217460  188 41110   2.95
217460  188 41130   5.9
217460  188 41160   5.9
217460  189 41110   11.8
217460  189 41130   8.85
217460  189 41160   11.8
217460  191 41130   5.95
217460  191 41160   8.93

这是一个非常大的数据集,我想要生成一个摘要输出,它给出了项目的总销售额和商品存在的商店数量。我尝试了以下方法,但这不起作用,因为我获得了由于数据集中重复数周而重复的存储计数:

代码语言:javascript
复制
dataset %>% group_by(Store ID) %>% summarize(count(Item Code))

任何帮助都是非常感谢的。谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-05-25 19:57:47

你可以用aggregate来做这件事

代码语言:javascript
复制
## Recreate your data
df = read.table(text="'Store ID'    'Week ID' 'Item Code'   'Sales in Dollars'
253422  191 41130   2.95
272568  188 41130   2.95
272568  188 41160   2.95
272568  189 41130   2.95
272568  189 41160   2.95
272568  190 41160   2.95
217460  188 41110   2.95
217460  188 41130   5.9
217460  188 41160   5.9
217460  189 41110   11.8
217460  189 41130   8.85
217460  189 41160   11.8
217460  191 41130   5.95
217460  191 41160   8.93",
header=TRUE)

aggregate(df$Sales.in.Dollars, list(df$Item.Code), sum)

组1 x 1 41110 14.75 2 41130 29.55 3 41160 35.48

代码语言:javascript
复制
StoreItems = unique(df[,c(1,3)])
aggregate(StoreItems$Store.ID, list(StoreItems$Item.Code), length)

组1 x 1 41110 1 2 41130 3 3 41160 2

票数 0
EN

Stack Overflow用户

发布于 2017-05-25 20:41:21

下面是一种使用dplyr实现这一任务的方法

代码语言:javascript
复制
library(dplyr)

df <- tibble::tribble(
  ~store_id, ~week_id, ~item_code, ~sales,
  253422L,     191L,     41130L,   2.95,
  272568L,     188L,     41130L,   2.95,
  272568L,     188L,     41160L,   2.95,
  272568L,     189L,     41130L,   2.95,
  272568L,     189L,     41160L,   2.95,
  272568L,     190L,     41160L,   2.95,
  217460L,     188L,     41110L,   2.95,
  217460L,     188L,     41130L,    5.9,
  217460L,     188L,     41160L,    5.9,
  217460L,     189L,     41110L,   11.8,
  217460L,     189L,     41130L,   8.85,
  217460L,     189L,     41160L,   11.8,
  217460L,     191L,     41130L,   5.95,
  217460L,     191L,     41160L,   8.93
)

df %>% 
  group_by(item_code) %>% 
  summarise(total_sales = sum(sales),
            stores = n_distinct(store_id))

#> # A tibble: 3 x 3
#>   item_code total_sales stores
#>       <int>       <dbl>  <int>
#> 1     41110       14.75      1
#> 2     41130       29.55      3
#> 3     41160       35.48      2
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44188515

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档