首页 > 解决方案 > 从字符串过滤到字符串

问题描述

这是我的数据框的 head():

date        id_station  zona  media_diaria max_diaria min_diaria sd_diaria count
2019-01-01  AJM         SO           0.339        0.5        0.2     0.114    18
2019-01-01  ATI         NO           0.439        0.9        0.2     0.238    18
2019-01-01  BJU         CE           0.667        1          0.4     0.235    18
2019-01-01  CAM         NO           0.611        1.2        0.2     0.356    18
2019-01-01  CCA         SO           0.55         0.8        0.3     0.195    18
2019-01-01  CHO         SE           0.541        1.6        0.1     0.511    17

我要做的是过滤从2019年3月1日(2019-03-01)到2020年2月29日(2020-02-29)的数据框。

我尝试了以下方法:

df <- df %>%
      filter(date %in% c(2019-03-01:2020-02-29))

但它总是返回一个空数据框。所以我尝试这样做,但将日期视为字符串:

df <- df %>%
      filter(date %in% c('2019-03-01':'2020-02-29'))

但它也返回一个空数据框。

标签: rstringdataframefilter

解决方案


我们可以使用between

library(dplyr)
df %>% 
  filter(between(date, as.Date('2019-03-01'), as.Date('2020-02-29')))

推荐阅读