2017-05-25 111 views
1

我有一個數據集,其中包含按出口每週銷售各種產品的數據集。下面是數據看起來的樣子:在R中彙總數據

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 

這是一個非常大的數據集,我想生成一個摘要輸出這使我的項目明智總銷售額中,該項目是目前的門店數量。我嘗試以下,但是,這並不工作,因爲我得到了門店數量這是由於數據集中的重複周的重複:

dataset %>% group_by(Store ID) %>% summarize(count(Item Code)) 

任何幫助,高度讚賞。 感謝

+0

可以格式化你的數據到一個表,使其更容易一點看它是什麼樣子? – Adam

+0

對不起@亞當,我的第一篇文章,我沒有意識到格式將是我發佈的方式可怕! – Rnovice

+0

https://stackoverflow.com/questions/1660124/how-to-sum-a-variable-by-group – Adam

回答

0

您可以aggregate

## 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) 
Group.1  x 
1 41110 14.75 
2 41130 29.55 
3 41160 35.48 
StoreItems = unique(df[,c(1,3)]) 
aggregate(StoreItems$Store.ID, list(StoreItems$Item.Code), length) 
Group.1 x 
1 41110 1 
2 41130 3 
3 41160 2 
+0

Thanks @ G5W!這對我有用! – Rnovice

1

做到這一點這裏有一個辦法做到這一點使用dplyr


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