两个日期之间的月数 [英] Number of months between two dates
问题描述
有没有一个标准/常用的方法/公式来计算R中两个日期之间的月份数?
Is there a standard/common method/formula to calculate the number of months between two dates in R?
我正在寻找类似于 MathWorks月份功能
推荐答案
我刚才说的很简单,但在几周内, difftime()
停止。多么奇怪
I was about to say that's simple, but difftime()
stops at weeks. How odd.
所以一个可能的答案就是把这些东西搞砸了:
So one possible answer would be to hack something up:
# turn a date into a 'monthnumber' relative to an origin
R> monnb <- function(d) { lt <- as.POSIXlt(as.Date(d, origin="1900-01-01")); \
lt$year*12 + lt$mon }
# compute a month difference as a difference between two monnb's
R> mondf <- function(d1, d2) { monnb(d2) - monnb(d1) }
# take it for a spin
R> mondf(as.Date("2008-01-01"), Sys.Date())
[1] 24
R>
似乎是正确的。可以将它包装成一些简单的类结构。或者将其作为一个黑客:)
Seems about right. One could wrap this into some simple class structure. Or leave it as a hack :)
编辑:也似乎适用于Mathworks中的示例:
Also seems to work with your examples from the Mathworks:
R> mondf("2000-05-31", "2000-06-30")
[1] 1
R> mondf(c("2002-03-31", "2002-04-30", "2002-05-31"), "2002-06-30")
[1] 3 2 1
R>
添加 EndOfMonth
标志留作练习给读者:)
Adding the EndOfMonth
flag is left as an exercise to the reader :)
编辑2:可能 difftime
将其作为没有可靠的方式来表达分数差异,这与其他单位的 difftime
行为一致。
Edit 2: Maybe difftime
leaves it out as there is no reliable way to express fractional difference which would be consistent with the difftime
behavior for other units.
这篇关于两个日期之间的月数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!