dose1 <- c("2022-08-21","2022-09-21","2022-10-21","2022-06-21","2022-09-21","2022-09-21")
dose2 <-c("2022-07-21","2022-09-21","2022-09-21","2022-10-21","2022-09-21","2022-09-21")
dose3 <- c("2022-02-21","2022-09-21","2022-09-21","2022-08-21","2022-09-21","2022-09-21")
count_dose1<- c("50","200","250","50","15","2")
count_dose2<- c("10","20","37","10","15","20")
count_dose3<- c("90","280","24","79","58","12")
df<- data.frame(dose1,dose2, dose3, count_dose1,count_dose2,count_dose3)
我想要从日期15-09-2022到15-10-2022的数据。我一直在寻找一种方法来根据所有三列的日期范围过滤数据。我能够通过df%>% filter(dose1 > as.Date('2022-09-15') & dose1 <as.Date('2022-10-15'))
一列接一列地完成它,请告诉我是否有任何方法可以创建一个数据框架,其日期范围从15-09-2022到15-10-2022。
您可以将filter
与dplyr
中的if_all
和between
一起使用:
library(dplyr)
df %>%
filter(if_all(dose1:dose3, ~ between(.x, as.Date('2022-09-15'), as.Date('2022-10-15'))))
dose1 dose2 dose3 count_dose1 count_dose2 count_dose3
1 2022-09-21 2022-09-21 2022-09-21 200 20 280
2 2022-09-21 2022-09-21 2022-09-21 15 15 58
3 2022-09-21 2022-09-21 2022-09-21 2 20 12