如何从R中的日期中减去月份?
我正在尝试从日期中减去 n 个月,如下所示:
I'm trying to subtract n months from a date as follows:
maturity <- as.Date("2012/12/31")
m <- as.POSIXlt(maturity)
m$mon <- m$mon - 6
但结果日期是 01-Jul-2012
,而不是 30-Jun-2012
,正如我所期望的.有没有什么捷径可以得到这样的结果?
but the resulting date is 01-Jul-2012
, and not 30-Jun-2012
, as I should expect.
Is there any short way to get such result?
提前致谢
1) seq.Date.请注意,6 月只有 30 天,因此它不能给出 6 月 31 日,而是给出了 7 月 1 日.
1) seq.Date. Note that June has only 30 days so it cannot give June 31st thus instead it gives July 1st.
seq(as.Date("2012/12/31"), length = 2, by = "-6 months")[2]
## [1] "2012-07-01"
如果我们知道是在月底,我们可以这样做:
If we knew it was at month end we could do this:
seq(as.Date(cut(as.Date("2012/12/31"), "month")), length=2, by="-5 month")[2]-1
## "2012-06-30"
2) 年月.此外,如果我们知道现在是月底,那么我们可以像这样使用动物园包的 "yearmon"
类:
2) yearmon. Also if we knew it was month end then we could use the "yearmon"
class of the zoo package like this:
library(zoo)
as.Date(as.yearmon(as.Date("2012/12/31")) -.5, frac = 1)
## [1] "2012-06-30"
这会将日期转换为 "yearmon"
减去 6 个月(一年的 0.5),然后使用 frac= 将其转换回
表示月底("Date"
1frac=0
表示月初).与之前的解决方案相比,这还具有自动矢量化的优点,即 as.Date(...)
可以是日期矢量.
This converts the date to "yearmon"
subtracts 6 months (.5 of a year) and then converts it back to "Date"
using frac=1
which means the end of the month (frac=0
would mean the beginning of the month). This also has the advantage over the previous solution that it is vectorized automatically, i.e. as.Date(...)
could have been a vector of dates.
请注意,如果 "Date"
类仅用作表示月份的一种方式,那么我们可以完全摆脱它并直接使用 "yearmon"
因为那建模我们首先想要的:
Note that if "Date"
class is only being used as a way of representing months then we can get rid of it altogether and directly use "yearmon"
since that models what we want in the first place:
as.yearmon("2012-12") - .5
## [1] "Jun 2012"
3) 星期一.第三种解决方案是 mondate 包,它的优点是它返回 6 个月前的月底,而不必知道我们是月底:
3) mondate. A third solution is the mondate package which has the advantage here that it returns the end of the month 6 months ago without having to know that we are month end:
library(mondate)
mondate("2011/12/31") - 6
## mondate: timeunits="months"
## [1] 2011/06/30
这也是矢量化的.
4) 润滑.此 lubridate 答案已根据包中的更改进行了更改:
4) lubridate. This lubridate answer has been changed in line with changes in the package:
library(lubridate)
as.Date("2012/12/31") %m-% months(6)
## [1] "2012-06-30"
lubridate 也是矢量化的.
lubridate is also vectorized.
5) sqldf/SQLite
library(sqldf)
sqldf("select date('2012-12-31', '-6 months') as date")
## date
## 1 2012-07-01
或者如果我们知道我们在月底:
or if we knew we were at month end:
sqldf("select date('2012-12-31', '+1 day', '-6 months', '-1 day') as date")
## date
## 1 2012-06-30