簡體   English   中英

按區域然后按自定義組匯總事件

[英]Summarize occurrences by area and then by custom groups

我有以下數據集,它采用 2 列數據集並根據規定的 CustomerAge 創建年齡組類別。

    library(tidyverse)
    
    df <- 
      read.table(textConnection("Area   CustomerAge
    A 28 
    A 40
    A 70
    A 19
    B 13
    B 12
    B 72
    B 90"), header=TRUE)
    

df2 <- df %>% 
  mutate(
    # Create categories
    Customer_Age_Group = dplyr::case_when(
      CustomerAge <= 18            ~ "0-18",
      CustomerAge > 18 & CustomerAge <= 60 ~ "19-60",
      CustomerAge > 60             ~ ">60"
    ))

我希望實現的是 output 摘要,如下所示:

區域 客戶_年齡_組 出現次數
一種 0-18歲 0
一種 19-59 3個
一種 >60 1個
0-18歲 2個
19-59 0
>60 2個

要包括 0 次出現,您需要count()ungroup()complete()

df2 %>% group_by(Area, Customer_Age_Group,.drop = FALSE) %>% 
count() %>% 
ungroup() %>% 
complete(Area, Customer_Age_Group, fill=list(n=0))

這也將顯示 0 次出現。

要按區域和年齡組排序:

df2 %>% group_by(Area, Customer_Age_Group,.drop = FALSE) %>% 
count() %>% 
ungroup() %>% 
complete(Area, Customer_Age_Group, fill=list(n=0)) %>% 
arrange(Area, parse_number(Customer_Age_Group))

group_bysummarise是你要找的。

df2 %>% group_by(Area, Customer_Age_Group) %>% summarise(Occurences = n())

但是請注意,這不會顯示數據集中出現次數為零的類別。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM