【问题标题】:Subtracting two dates in different formats in R在R中减去不同格式的两个日期
【发布时间】:2015-07-17 05:20:08
【问题描述】:

我正在尝试添加一个包含日期计算的新列。要在新列中输入的计算是变量 MaturityDate 减去今天的日期。 我的数据集中的 MaturityDate 采用 MM/DD/YYYY 格式,而使用 Sys.Date() 输入的今天日期采用不同的格式,我认为这是计算时给我带来麻烦的原因。 请帮忙!

【问题讨论】:

  • 确保两个值都是 R 中正确的 POSIX 日期值(请参阅?DateTimeClasses)。现在听起来像其中一个可能是一个因素或字符串。但是您确实需要发布一个reproducible example,其中包含与您自己非常相似的示例输入数据,以便我们了解发生了什么。

标签: r date


【解决方案1】:

使用包 lubridate 使日期操作变得容易。

library(lubridate)  
somedate <- mdy("3/14/2015")  
today <- now()  
somedate - today  

【讨论】:

    【解决方案2】:

    可以肯定的是,我会将日期转换为单一格式。

    date.to.numeric <- function(x) as.numeric(strptime(x,'%m/%d/%Y'))
    now <- function() as.numeric(strptime(Sys.Date(),'%Y-%m-%d'))
    

    这样,您可以使用秒数获得时差

    date.to.numeric(date) - now()
    

    如果您想要一些不同的东西(例如,日历月的差异),还可以查看 as.POSIXct 了解更多日期格式。

    【讨论】:

      【解决方案3】:

      当您的数据框称为 YourDataFrame 并且具有所需结果的新列应称为 newCol:

      YourDataFrame$newCol <- as.Date(MaturityDate, "%m/%d/%Y") - Sys.Date()
      

      【讨论】:

        【解决方案4】:

        对我来说效果很好的方法是使用 library(dplyr) 和 library(lubridate) 的组合,就像这样:

        dataset <-dataset %>% 
            mutate(MaturityDate=mdy(MaturityDate), #make sure to say what the format is first
            Sys.Date=mdy(Sys.Date)) %>%
            mutate(difference=as.numeric(difftime (Sys.Date, MaturityDate, units = "days")))
        

        这给出了这样的结果:

        head(dataset,2)
        
        > MaturityDate     Sys.Date     difference
        > 2018-05-05      2018-05-26    50
        > 2018-06-06      2018-06-10    48 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-11-17
          • 1970-01-01
          • 2012-06-07
          • 2020-02-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多