如何计算R中的月差

how to calculate month difference in R

我有 2015-03 格式的日期(即年月)。现在我想计算两个日期之间的月份差异。

示例:日期 2015-032014-12 之间的差异应为 3 或 4,因为 12 月到 3 月是 3 个月或 4 个月,具体取决于我们是否考虑 12 月。

您可以通过 diff

完成
require(lubridate)
a <- c("2015-03","2014-12")
a_parsed <- ymd(paste0(a,"-01")) # There might be a nicer solution to get the dates

diff(year(a_parsed)) * 12 + diff(month(a_parsed)) # Results in 3

使用+ 1到"consider December"

解释:
diff(year(a_parsed)) 给出了年份的差异,* 12 给出了由此产生的月份。 diff(month(a_parsed)) 导致月差,忽略年差。将它结合起来就可以得出您要求的每月差异。

a <- "2015-03"
b <- "2014-12"
a <- unlist(strsplit(a, "-"))
b <- unlist(strsplit(b, "-"))
a <- (as.numeric(a[1])*12) + as.numeric(a[2])
b <- (as.numeric(b[1])*12) + as.numeric(b[2])
difference <- diff(c(b,a))
difference

结果是 3