计算data.table中两个日期之间的月份

时间:2017-07-19 08:18:52

标签: r data.table datediff

我有data.table,如下所示:

ID   start_date   end_date
1    2015.01.01   2016.02.01 
2    2015.06.01   2016.03.01
3    2016.01.01   2017.01.01

我想得到以下内容:

ID   start_date   end_date    Months_passed
1    2015.01.01   2016.02.01  13
2    2015.06.01   2016.03.01   9
3    2016.01.01   2017.01.01  12

我正在尝试以下代码:

DT[, Months_passed:= length(seq(from = start_date, to = end_date, by='month')) - 1]

但我得到了错误,

  

“seq.Date中的错误(from = start_date,to = end_date,by =”month“):     'from'必须长度为1“

1 个答案:

答案 0 :(得分:5)

这是使用data.table的可能方法。首先,将您的日期转换为实际日期格式:

df[, 2:3 := lapply(.SD, as.IDate, format = "%Y.%m.%d"), .SDcols = 2:3]

然后,过去几个月:

df[, months_passed := lengths(Map(seq, start_date, end_date, by = "months")) -1]

所以基本上你需要Map seq的开始和结束日期。

结果是:

df
#   ID start_date   end_date months_passed
#1:  1 2015-01-01 2016-02-01            13
#2:  2 2015-06-01 2016-03-01             9
#3:  3 2016-01-01 2017-01-01            12