计算data.table中两个日期之间的月份 [英] Count the months between two dates in a data.table
本文介绍了计算data.table中两个日期之间的月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 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
"Error in seq.Date(from = start_date, to = end_date, by = "month") : 'from' must be of length 1"
推荐答案
这是使用data.table的一种可能方法。首先,将您的日期转换为真实的日期格式:
Here's a possible approach using data.table. First, turn your dates to real date-format:
df[, 2:3 := lapply(.SD, as.IDate, format = "%Y.%m.%d"), .SDcols = 2:3]
然后,获取通过的月份:
Then, get the months that passed:
df[, months_passed := lengths(Map(seq, start_date, end_date, by = "months")) -1]
因此,基本上,您需要将
开始日期和结束日期映射到 seq
。
So basically you need to Map
the start and end dates to 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
这篇关于计算data.table中两个日期之间的月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文