问题描述
我有一个脚本,其中我可以按照设置的时间段对数据进行子集化,并希望对上个月发生的所有记录进行子集化.
I have a script in which I subset my data according to some set time periods and wanted to subset all the records that had occurred in the last month.
但是,如果我尝试从今天的日期减去一个月,则会得出NA:
However if I try to subtract one month from today's date it yields an NA:
> today <- Sys.Date()
> today
[1] "2017-03-29"
> today - months(1)
[1] NA
我确实已加载润滑脂,但我认为此计算是在基数R的情况下进行的.如果我减去2个月或更长时间,它会正常工作:
I do have lubridate loaded but I think this calculation is being performed with base R. If I subtract 2 or more months it works fine:
> today - months(2)
[1] "2017-01-29"
> today - months(3)
[1] "2016-12-29"
有人对可能发生的事情有任何想法吗?
Does anyone have any ideas about what might be going on?
更新:我认为这与不处理leap年案例的简单日期减法有关(2017年不是a年,因此"2017-02-29"
不存在).
UPDATE: I think this is something to do with simple date subtraction not handling leap year cases (2017 is not a leap year so "2017-02-29"
does not exist).
是否还有其他考虑leap年的软件包/功能?对于上面的示例,我希望答案恢复为上个月的最后一天,即:
Are there other packages / functions that take into account leap years? For the above example I would expect the answer to revert to the last day of the previous month, i.e.:
today - months(1)
# Should yield:
"2017-02-28"
这种计算对于今天和昨天给出相同的结果(或对此的ISO约定)是否有意义?
Would it make sense for this calculation to give the same results for both today and yesterday (or what is the ISO convention for this)?
> sessionInfo()
R version 3.3.2 (2016-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
locale:
[1] LC_COLLATE=English_United Kingdom.1252 LC_CTYPE=English_United Kingdom.1252
[3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] xlsx_0.5.7 xlsxjars_0.6.1 rJava_0.9-8 MRAtools_0.6.8 stringdist_0.9.4.4 stringr_1.2.0
[7] stringi_1.1.3 lubridate_1.6.0 data.table_1.10.4 PKI_0.1-3 base64enc_0.1-3 digest_0.6.12
[13] getPass_0.1-1 RPostgreSQL_0.5-1 DBI_0.5-1
loaded via a namespace (and not attached):
[1] magrittr_1.5 rstudioapi_0.6 tools_3.3.2 parallel_3.3.2
推荐答案
月份的计算确实是由基数R决定的,而不是您的思维方式.月份用于获取日期对象的月份.
The calculation of months is indeed perfomed by base R but not the way your think. Months is used to get the month of a date object.
#Example
today <- Sys.Date()
months(today)
[1] "March"
要添加或减去月份,应使用lubridate
中的%m+%
:
To add or substract months, you should use %m+%
from lubridate
:
today <- Sys.Date()
today %m+% months(-1)
[1] "2017-02-28"
这篇关于R从今天的日期减去1个月得出NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!