【问题标题】:Aggregate Two Variables by One Date按一个日期聚合两个变量
【发布时间】:2020-06-01 15:49:16
【问题描述】:

我正在使用以下数据集:

     day descent_cd
   <int> <chr>     
 1    26 B         
 2    19 W         
 3    19 B         
 4    16 B         
 5     1 W         
 6     2 W         
 7     2 B         
 8     2 B         
 9     3 W         
10     3 W         
# … with 1,283 more rows

简而言之:“day”变量是一个月中的哪一天。 “Descent_cd”是种族(黑色或白色)。

我正在尝试对其进行组织,以便获得“B”列和“W”列,两者均按当天的总逮捕次数排序......意思是:计算第“1天”的所有“B” " 和 "W" 一样,然后在本月剩下的时间里以此类推。

我最终希望将其作为 geom_ridge 图。

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

    这是你要找的吗?

    library(tidyverse)
    #sample data
    df <- tibble::tribble(
      ~day, ~descent_cd,
        26L,      "B",
       19L,         "W",
       19L,         "B",
       16L,         "B",
        1L,         "W",
        2L,         "W",
        2L,         "B",
        2L,         "B",
        3L,         "W",
        3L,         "W"
      )
    
    df %>% 
      group_by(day, descent_cd) %>% 
      summarise(total_arrest = n()) %>% #calculate number of arrests per day per descent_cd
      pivot_wider(names_from = descent_cd, values_from = total_arrest) %>% #create columns W and B
      mutate(W = if_else(is.na(W),as.integer(0),W), #replace NAs with 0 (meaning 0 arrests that day)
             B = if_else(is.na(B),as.integer(0),B)) %>% 
      arrange(desc(wt = W+B)) #arrange df in descending order of total arrests per day
    
    # A tibble: 6 x 3
    # Groups:   day [6]
        day     W     B
      <int> <int> <int>
    1     2     1     2
    2     3     2     0
    3    19     1     1
    4     1     1     0
    5    16     0     1
    6    26     0     1
    
    

    【讨论】:

    • 格式化它的效果很好。您知道如何为 geom_density_ridges 构建它吗?自从你帮我解决第一个问题以来一直在玩它,但仍然无法实现它。
    • 像这样:? df %&gt;% ggplot(aes(x = day, y = descent_cd)) + geom_density_ridges()(但使用您发布的 df 的格式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    相关资源
    最近更新 更多