【问题标题】:Date comparison with System Date in R日期与 R 中的系统日期比较
【发布时间】:2018-03-07 09:23:54
【问题描述】:

我想比较一列中的数据,即结束日期(end_date)和系统日期(todays_date)。两列都是 char 格式。

Input:
$ name: chr  "Abby" "Abby" "Abby" "Abby" ...
$ std: int  2 3 4 5 6 7 8 9 10 11 ...
$ end_date: chr  "25-02-2016" "25-02-2016" "25-03-2018" "25-02-2019" ...
$ todays_date: chr  "07-03-2018" "07-03-2018" "07-03-2018" "07-03-2018" ...

有什么方法可以传递sqldf 语句,我可以在其中获取输入 csv 的所有值,其中 end_date sqldf 语句之外的任何方式,我都可以提取 csv 的值,其中 end_date

我尝试了以下查询的一些可能变化,但似乎无法获得所需的输出:

sel_a <- sqldf(paste("SELECT * FROM input_a WHERE end_date<", 
todays_date, "", sep = ""))
sel_a

PS:我有大量数据并已将其减少以适应这个问题。

任何帮助将不胜感激。

【问题讨论】:

    标签: r date compare


    【解决方案1】:

    要获得更具体的答案,请发送reproducible example

    将日期列从字符转换为日期时间对象,例如,使用

    library(lubridate)
    your_df$end_date <- mdy(your_df$end_date)
    

    那么,你甚至不需要今天日期的列,只需将其用作过滤条件

    library(dplyr)
    filter(your_df, end_date < Sys.Date())
    # will return a data frame with those rows that have a date before today.
    

    或者,如果您愿意:

    your_df[your_df$end_date < Sys.Date(),]
    # produces the same rows
    

    【讨论】:

    • 我使用 as.Date 转换 end_date ,然后使用 your_df[your_df$end_date
    【解决方案2】:

    使用末尾注释中显示的原始输入,首先将日期转换为"Date" 类,然后使用显示的任何替代方法。前两个在输入中使用end_date,最后两个使用Sys.Date()。我们展示了sqldf 和基本解决方案。

    library(sqldf)
    fmt <- "%d-%m-%Y"
    Input <- transform(Input_raw, end_date = as.Date(end_date, fmt),
                                  todays_date = as.Date(todays_date, fmt))
    
    # 1
    sqldf("select * from Input where end_date <= todays_date")
    
    # 2
    subset(Input, end_date <= todays_date)
    
    # 3
    fn$sqldf("select * from Input where end_date <= `Sys.Date()`")
    
    # 4
    subset(Input, end_date <= Sys.Date())
    

    注意

    Input 的可重现形式:

    Input_raw <- data.frame(name = "Abby", std = 2:5, 
      end_date = c("25-02-2016", "25-02-2016", "25-03-2018", "25-02-2019"),
      todays_date = "07-03-2018", stringsAsFactors = FALSE)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      • 2021-04-24
      • 2015-07-25
      相关资源
      最近更新 更多