这个问题是这样的扩展问题。本质上,我试图根据用户选择来过滤日期。我能够获得2018年和2019年的正确输出。但是,当我选择Year作为0时,输出显示的是2018年,2019年和0年的数据。我只想看到用户选择2019年时,应显示与2019相关的数据,包括2018和0。当用户选择2018时,输出应与2018年和0相关。但是,当用户选择0年时,仅与0年相关的数据应被过滤并显示。下面的代码没有做。
任何帮助表示赞赏!
资料集:
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)
也许您可以尝试filter
将year
以下所有数字
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来实现
select_data <- function(d, num) {
subset(d, year <= num)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句