如何在R中使用Dplyr过滤年初至今的数据? [英] How to filter Year-to-date data using Dplyr in R?

查看:54
本文介绍了如何在R中使用Dplyr过滤年初至今的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是这个问题。本质上,我试图根据用户选择过滤日期。我能够获得2018年和2019年的正确输出。但是,当我选择Year作为0时,输出显示的是2018年,2019年和0年的数据。我想看到的是用户选择2019年的情况,应显示与2019相关的数据,包括2018和0。当用户选择2018时,输出应与2018年和0相关。但是,当用户选择0年时,仅应过滤和显示与0年相关的数据。

This question is extension of this question. Essentially, I am trying to filter dates based on user selection. I was able to get correct output for the year 2018 and 2019. However, when I select Year as 0, the output is displaying data from the year 2018,2019 and 0. All I want to see is when user selects year 2019, It should show data related to 2019 including 2018 and 0. When user selects 2018, the output should be related to year 2018 and 0. However, when user selects year 0, only data related to year 0 should be filtered and display. Which below code is not doing.

感谢任何帮助!

数据集:

structure(list(Systems = c("Sys1", "Sys1", "Sys2", "Sys3", "Sys4", 
"Sys6", "Sys7"), Locations = c("loc1", "loc1", "loc1", "loc2", 
"loc2", "loc3", "loc1"), year = c(2018, 2019, 2019, 2019, 2019, 
0, 0), frequency = c(1L, 2L, 1L, 1L, 1L, 0L, 0L), freq_cal = c(33.33, 
66.67, 100, 100, 100, 0, 0), label = c("33.33%", "66.67%", "100.00%", 
"100.00%", "100.00%", "0.00%", "0.00%")), row.names = c(NA, -7L
), class = "data.frame")

用于过滤的代码:

d %>%
  filter(year<=2019 |year==0) 


推荐答案

也许您可以尝试对以下的所有进行过滤数字

Maybe you could try to filter all the year below a certain number

library(dplyr)

select_data <- function(d, num) {
   d %>% filter(year <= num) 
}

select_data(d, 2019)

#  Systems Locations year frequency freq_cal   label
#1    Sys1      loc1 2018         1    33.33  33.33%
#2    Sys1      loc1 2019         2    66.67  66.67%
#3    Sys2      loc1 2019         1   100.00 100.00%
#4    Sys3      loc2 2019         1   100.00 100.00%
#5    Sys4      loc2 2019         1   100.00 100.00%
#6    Sys6      loc3    0         0     0.00   0.00%
#7    Sys7      loc1    0         0     0.00   0.00%

select_data(d, 2018)
#  Systems Locations year frequency freq_cal  label
#1    Sys1      loc1 2018         1    33.33 33.33%
#2    Sys6      loc3    0         0     0.00  0.00%
#3    Sys7      loc1    0         0     0.00  0.00%

select_data(d, 0)
#  Systems Locations year frequency freq_cal label
#1    Sys6      loc3    0         0        0 0.00%
#2    Sys7      loc1    0         0        0 0.00%

同样的逻辑也只能使用基数R来实现

The same logic can be implemented only using base R as well

select_data <- function(d, num) {
   subset(d, year <= num)
}

这篇关于如何在R中使用Dplyr过滤年初至今的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆