过滤数据并计算输出依赖于排除数据的子集

Filtering data and calculating for subsets with the output dependent on excluded data

我有一个数据框,其中月度数据 month 关于食草动物寄生 result 的各种寄生蜂目 'psitorder' 水平 "Hymenoptera" 或 "Diptera" . result是被寄生的食草动物"p",如果食草动物长大成年则"a",或者没有数据“”因为食草动物在圈养中死亡。

  df<-data.frame(month= c(rep(1, each=8), rep(2, each=6), 
      rep(3, each=6)),result= c(rep("p",each=3),rep("a",each=3) , 
      rep("",each=2),rep("p",each=3),rep("a",each=2), 
      rep("",each=1),rep("a",each=3), rep("",each=3)),
      psitorder= c(rep("Hymenoptera",each=2),rep("Diptera",each=1),
      rep("",each=5),rep("Hymenoptera",each=1),rep("Diptera",each=3), 
      rep("",each=2),rep("",each=6)))

我需要两个单独的数据框,分别为 psitorder 的每个级别计算每个月子集的寄生百分比 psit_freq

我试过:

Hymenoptera_output<- 
  df  
  filter(psitorder!= "Diptera")%>%
  group_by(continuous_month)%>%
  summarise(psit_freq = sum(result == "psit")/sum(result== 
 "adult",result == "psit"))

Diptera_output<- 
  df  
  filter(psitorder!= "Hymenoptera")%>%
  group_by(continuous_month)%>%
  summarise(psit_freq = sum(result == "psit")/sum(result== 
 "adult",result == "psit"))

我没有得到正确的输出。输出不包括正确计算 psit_freq 所需的非膜翅目或双翅目数据。

我需要如下所示的输出:

Hymenoptera_output<- data.frame(month= c(1,2,3), psit_freq= c(2/6, 
 1/5, 0))
Diptera_output<- data.frame(month= c(1,2,3), psit_freq= c(1/6, 
 3/5, 0))

Hymenoptera_output

#  month psit_freq
#1     1 0.3333333
#2     2 0.2000000
#3     3 0.0000000

Diptera_output

#  month psit_freq
#1     1 0.1666667
#2     2 0.6000000
#3     3 0.0000000

您似乎需要:

df %>% 
    group_by(month) %>% 
    summarise(hym_freq = sum(psitorder == 'Hymenoptera')/sum(result %in% c('p', 'a')), 
              dip_freq = sum(psitorder == 'Diptera')/sum(result %in% c('p', 'a')))

# A tibble: 3 x 3
#  month  hym_freq  dip_freq
#  <dbl>     <dbl>     <dbl>
#1     1 0.3333333 0.1666667
#2     2 0.2000000 0.6000000
#3     3 0.0000000 0.0000000