【问题标题】:Filter by specific range of dates in R [duplicate]按R中的特定日期范围过滤[重复]
【发布时间】:2021-07-17 22:49:03
【问题描述】:
ID    Date     Score
17   4/3/2020   13
18   6/2/2021   90
3    7/2/2019   15
4    8/1/2020   87
5    8/9/2020   78
20   6/7/2020   18
19   5/4/2020   55
17   5/29/2020  44

我只想保留从 2020 年 4 月 1 日到 2020 年 6 月 30 日的行,以便最终的 df 为:

   ID    Date     Score
    17   4/3/2020   13
    18   6/2/2021   90
    20   6/7/2020   18
    19   5/4/2020   55
    17   5/29/2020  44

【问题讨论】:

标签: r dataframe date


【解决方案1】:

使用 tidyverse 和 lubridate,试试

library(lubridate)
library(tidyverse)

df <- 
  data.frame(ID = c(17, 18, 3, 4, 5, 20, 19, 17), 
             Date = c("4/3/2020", "6/2/2021", "7/2/2019", "8/1/2020", "8/9/2020", "6/7/2020", "5/4/2020", "5/29/2020"), 
             Score = c(13, 90, 15, 87, 78, 18, 55, 44))

df %>% 
 mutate(Date = lubridate::mdy(Date)) %>% 
 filter(Date > as.Date("2020-04-01"), 
        Date < as.Date("2020-06-30"))

# A tibble: 4 x 3
     ID Date       Score
  <dbl> <date>     <dbl>
1    17 2020-04-03    13
2    20 2020-06-07    18
3    19 2020-05-04    55
4    17 2020-05-29    44

【讨论】:

    【解决方案2】:

    如果您将数据存储在名为 df 的 data.frame 或 tibble 中,则可以使用 lubridate 和 dplyr 包对数据进行子集化:

    library(dplyr)
    library(lubridate)
    
    df %>%
      filter(mdy(`Date`) >= as.Date('2020-04-01') & mdy(`Date`) <= as.Date('2020-06-30'))
    

    【讨论】:

      【解决方案3】:

      使用末尾注释中可重复显示的数据将日期转换为 yearqtr(表示年份和季度的类,然后提取指定的类)。

      library(zoo)
      subset(dat, as.yearqtr(Date, "%m/%d/%Y") == "2020 Q2")
      

      给予:

        ID      Date Score
      1 17  4/3/2020    13
      6 20  6/7/2020    18
      7 19  5/4/2020    55
      8 17 5/29/2020    44
      

      这也适用于 yearqtr 使用内部表示年 + 分数,其中四个季度的分数分别为 0、0.25、0.5 和 0.75。

      subset(dat, as.yearqtr(Date, "%m/%d/%Y") == 2020.25)
      

      注意

      Lines <- "ID    Date     Score
      17   4/3/2020   13
      18   6/2/2021   90
      3    7/2/2019   15
      4    8/1/2020   87
      5    8/9/2020   78
      20   6/7/2020   18
      19   5/4/2020   55
      17   5/29/2020  44"
      dat <- read.table(text = Lines, header = TRUE)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-25
        相关资源
        最近更新 更多