r - 使用 dplyr 过滤器过滤多个条件的意外输出
问题描述
我有一个包含 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) 将返回条件 1 为真但条件 2 不为真的所有行。
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 年的值)。
我不确定我是否只是不了解如何使用过滤器。任何帮助将非常感激。
解决方案
将其添加到构面内。
facet_grid(~ report_epiyear, scales = "free", space = "free" )
推荐阅读
- python - Python 多个条件与 if else 语句?[已解决的案例]
- google-chrome-extension - Chrome 扩展应用程序有时会丢失本地存储
- google-maps - Google 如何在不使用移动互联网数据计划的情况下跟踪我?
- docker - 如何向我的 docker buildx 构建器添加对 mips 的支持?
- javascript - 复数包含数组的对象键
- c++ - 不能给出一个前导零的数字来运行吗?
- javascript - iOS 仅在背景元素的 CSS 设置为 cursor:pointer 时检测 mouseleave
- javascript - 如何在滚动时将此 JQuery 转换为 Vanilla JS
- c# - 如何在 ASP.net 中引用 HTML 元素?
- python-3.x - 在python中使用字典计算总分和排名