【问题标题】:Unexpected output from Filtering Multiple Conditions with dplyr filter使用 dplyr 过滤器过滤多个条件的意外输出
【发布时间】:2019-09-21 05:48:54
【问题描述】:

我有一个包含 3 个变量的数据框:report_epiweek、report_epiyear 和 Freq_case。

library(dplyr)
library(ggplot2)    
mydata<-data.frame(report_epiweek=c(1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10), 
                       report_epiyear=c(2018,2018,2018,2018,2018,2018,2018,2018,2018,2018,2019,2019,2019,2019,2019,2019,2019,2019,2019,2019), 
                       Freq_case=c(0,0,0,0,0,0,2,6,2,3,4,5,7,8,34,2,0,6,3,1))

我想用 ggplot2 制作一个条形图。我想从 2018 年(第 1 周到第 6 周)过滤掉值为 0 的周。我对过滤功能的理解是可以根据多个条件过滤行(来自https://suzan.rbind.io/2018/02/dplyr-tutorial-3/):

基于多个条件的过滤 上述示例基于单个条件返回行,但过滤器选项还允许 AND 和 OR 样式过滤器:

filter(condition1, condition2) 将返回同时满足两个条件的行。

filter(condition1, !condition2) 将返回条件一为真但条件二不为真的所有行。

filter(condition1 | condition2) 将返回满足条件 1 和/或条件 2 的行。

filter(xor(condition1, condition2) 将返回仅满足一个条件的所有行,而不是同时满足两个条件的所有行。

mydata %>% 
  mutate(report_epiweek=as.numeric(report_epiweek)) %>% 
  filter(!Freq_case==0 & report_epiyear==2018) %>%
  ggplot(aes(x=report_epiweek, y=Freq_case))+
  geom_col()+
  ggtitle("EpiCurve") + 
  facet_grid(. ~ report_epiyear)+ 
  theme_bw()+ 
  theme(axis.text.x = element_text(angle = 90), legend.position = "bottom", legend.title = element_text(color = "black", size = 8))

这会产生以下图表。

过滤器似乎正在过滤掉所有具有 2018 年 report_epiyear 的记录,但我想要一个图表,其中过滤的记录是那些 Freq_case 为 0 并且在 2018 年的记录。这将使我的 Freq_case 0 2019 年未受影响。 (我将能够看到其他 2018 年的值)。

我不确定我是否只是不了解如何使用过滤器。任何帮助将不胜感激。

【问题讨论】:

    标签: r filter dplyr


    【解决方案1】:

    您所写的! 仅适用于第一个参数(Freq==0)。在 &amp; 条件的两个组件周围添加括号,以便在使用 ! 反转它之前它们是联合的。

    mydata %>% 
      mutate(report_epiweek=as.numeric(report_epiweek)) %>% 
      filter(!(Freq==0 & report_epiyear==2018)) %>%
      ggplot(aes(x=report_epiweek, y=Freq))+
      geom_col()+
      ggtitle("EpiCurve") + 
      facet_grid(. ~ report_epiyear)+ 
      theme_bw()+ 
      theme(axis.text.x = element_text(angle = 90), legend.position = "bottom", legend.title = element_text(color = "black", size = 8))
    

    【讨论】:

    • 我试过你的建议;前 5 周仍显示在图表上。
    • 哪一年?我已经上传了我的回答所产生的情节图片。
    • 我得到了相同的输出。我希望没有 2018 年的前 6 周(抱歉我之前说过 5 周),其中 Freq_case=0
    • 不,我明白你在找什么。我使用了您相同的数据集,并且我的答案中的代码生成了上面的图,我相信这就是您要寻找的,对吗?
    【解决方案2】:

    在构面内添加这个。

    facet_grid(~ report_epiyear, scales = "free", space = "free" )

    【讨论】:

      猜你喜欢
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      • 2020-04-17
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      相关资源
      最近更新 更多