【问题标题】:Comparing two dates with different formats比较具有不同格式的两个日期
【发布时间】:2016-11-23 11:38:34
【问题描述】:

我需要比较以下数据集的两个日期:

structure(list(date = c(20160919L, 20161108L, 20160217L), TagActivationDate = structure(c(24L, 
42L, 9L), .Label = c("1/10/2016", "1/11/2016", "10/10/2016", 
"10/11/2016", "11/08/2016", "11/10/2016", "11/11/2016", "12/10/2016", 
"12/11/2016", "13/10/2016", "13/11/2016", "14/10/2016", "14/11/2016", 
"15/10/2016", "16/10/2016", "17/10/2016", "18/10/2016", "19/08/2016", 
"19/10/2016", "2/10/2016", "20/10/2016", "21/10/2016", "22/10/2016", 
"23/09/2016", "23/10/2016", "24/09/2016", "24/10/2016", "25/09/2016", 
"25/10/2016", "26/10/2016", "27/10/2016", "28/09/2016", "28/10/2016", 
"29/09/2016", "29/10/2016", "3/10/2016", "30/09/2016", "30/10/2016", 
"31/10/2016", "4/10/2016", "5/10/2016", "5/11/2016", "6/10/2016", 
"6/11/2016", "7/11/2016", "8/10/2016", "8/11/2016", "9/10/2016", 
"9/11/2016"), class = "factor")), .Names = c("date", "TagActivationDate"
), row.names = c(NA, 3L), class = "data.frame")

其中一个是整数,另一个是因子,如果它们有超过两天的差异,我需要标记它们:

mydata$filtcases <- mydata$date >= ( mydata$TagActivationDate - 2)

我尝试将它们转换为不同的格式,但都没有成功。任何提示表示赞赏。

【问题讨论】:

  • 那么所有的预期输出都是TRUE
  • 在这个例子中是
  • 将两者转换为相同的日期格式,然后得到差异。
  • library(lubridate); abs(ymd(x$date) - dmy(x$TagActivationDate)) &gt; 2 ?

标签: r datetime


【解决方案1】:

正如@zx8754 提到的,尝试让它们都采用相同的格式,然后找出它们之间的区别

abs(as.Date(as.character(df$date), "%Y%m%d") - 
                as.Date(as.character(df$TagActivationDate), "%d/%m/%Y")) > 2
#[1] TRUE TRUE TRUE

【讨论】:

    【解决方案2】:

    使用润滑:

    library(lubridate)
    
    mydata$filtcases <- abs(ymd(mydata$date) - dmy(mydata$TagActivationDate)) > 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多