在R中减去不同格式的两个日期

时间:2015-05-06 21:02:10

标签: r date

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

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

我会将日期转换为单一格式以确定。

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以获取更多日期格式。

答案 2 :(得分:0)

当您的数据框被调用YourDataFrame时,应该调用具有所需结果的新列newCol

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

答案 3 :(得分:0)

一种对我来说效果很好的方法是使用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