R 按一个日期聚合两个变量

R 按一个日期聚合两个变量,r,tidyverse,R,Tidyverse,我正在使用以下数据集: 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

我正在使用以下数据集:

     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
日间下降\u cd
126b
2 19西
319b
4 16 B
5.1瓦
6.2瓦
7.2 B
8.2 B
9 3 W
10 3瓦
#…还有1283行
简而言之,“day”变量是一个月中的哪一天。“下降cd”是种族(黑色或白色)

我正试图组织它,这样我就可以得到一个“B”栏和一个“W”栏,这两个栏都是按当天逮捕的总人数排序的。。。意思是:计算“1”天的所有“B”,计算“W”的所有“B”,然后依次类推,直到这个月剩下的时间


我最终想做一个几何脊图。

这就是你想要的吗

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

库(tidyverse)
#样本数据
df%
分组依据(日期、下降天数)%>%
总结(总逮捕人数=n())%>%#计算每次下降每天的逮捕人数
pivot_wider(name_from=descent_cd,values_from=total_Restrict)%>%#创建W列和B列
变异(W=if_else(is.na(W),as.integer(0),W),#将NAs替换为0(表示当天0次逮捕)
B=如果_else(is.na(B),as.integer(0),B))%>%
安排(描述(wt=W+B))#按每天总逮捕人数的降序安排df
#一个tibble:6x3
#分组:第[6]天
第W天B
1     2     1     2
2     3     2     0
3    19     1     1
4     1     1     0
5    16     0     1
6    26     0     1

这项功能非常适合格式化它。你知道如何构造几何密度脊吗?自从你帮我解决了第一个问题后,我就一直在玩弄它,但仍然无法实现。像这样:
df%>%ggplot(aes(x=day,y=densition\u cd))+geom\u density\u ridges()
(但格式为您发布的
df
)。