减少月份 - 与最后一个月的问题? [英] Subtracting months - issue with last day of month?

查看:116
本文介绍了减少月份 - 与最后一个月的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中的日期的快速问题。查看这段代码:

Quick question on dates in R. Check out this snippet of code:

Sys.Date() - months(3)
# [1] "2013-12-31"
Sys.Date() - months(18)
# [1] NA

我已经加载了 lubridate ,并按照提供的说明,我不能完全弄清楚这个行为。以前工作很好,今天是第一天,我注意到从今天起扣减了12个月以上,收到 NA (扣除少于12个月的工作正常)

I've loaded the package lubridate and followed the instructions provided , and I can't quite get my head around this behavior. It used to work just fine, today's the first day that I've noticed that a subtraction of more than 12 months from today's date yields NA (subtracting less than 12 months works fine).

如果有人可以向我解释为什么这不工作,和/或建议一个更强壮的方式,我将不胜感激。这是否与今天的最后一天(第31天)有关?

I'd appreciate if anyone can explain to me why this isn't working, and/or suggest a more "robust" way around it. Does it have something to do with today being the last day of the month (day 31)?

我问这是因为这样做:

Sys.Date() - years(2)
# [1] "2012-03-31"


推荐答案

lubridate $ c>%m +%和%m - %旨在处理此问题(添加和减去几个月到不超过最后

The lubridate functions %m+% and %m-% are designed to handle this issue ("Add and subtract months to a date without exceeding the last day of the new month").

library(lubridate)
Sys.Date() %m-% months(18)
# [1] "2012-09-30"

# or to make it reproducible if Sys.Date() happens to be different from that in OP
as.Date("2014-03-31") %m-% months(18)
# [1] "2012-09-30"

# example of %m+%
as.Date("2014-01-31") + months(1)
# [1] NA
as.Date("2014-01-31") %m+% months(1)
# [1] "2014-02-28"

这篇关于减少月份 - 与最后一个月的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆