【问题标题】:Does lubridate have a function similar to the yearmon function of zoo?lubridate 有没有类似于 zoo 的 yearmon 功能?
【发布时间】:2017-04-21 03:42:33
【问题描述】:

我正在处理一个带有月份变量的 data.frame,该变量只有年和月部分。我的部分数据如下:

     month         DIV  MKTP
1  1941-12 0.005752218 -4.87
2  1942-01 0.005767111  0.79
3  1942-02 0.005781771 -2.46
4  1942-03 0.005859665 -6.58
5  1942-04 0.005906924 -4.37
6  1942-05 0.005890041  5.94
7  1942-06 0.005941640  2.69
8  1942-07 0.005962464  3.51
9  1942-08 0.005936732  1.80
10 1942-09 0.006007593  2.61

我想将月份变量转换为 yearmon 格式以进行子集化。我的代码如下:

require(zoo,dplyr)
  df %>%
  mutate(month = as.yearmon(month)) %>%
  filter(month >= as.yearmon("1942-3") & month <= as.yearmon("1942-8"))

我想知道 lubridate 包是否具有与 yearmon 类似的功能,可以输入年份和月份的组合。

【问题讨论】:

  • 我刚刚修改了我的代码以使其适合示例

标签: r lubridate


【解决方案1】:

Here are lubridate's functions 答案是否定的,因为lubridate 用于处理日期并且日期有天数。您可以假设日期为 01 并使用 ymd 转换为日期格式,或者只使用 zoo::yearmon

【讨论】:

  • 或者使用anytime::anydate("1941-12"),也假设day = 1
  • 如果是这样,你如何解释yq()函数...?
  • 我将其解释为 (1) 隐藏在 ymd 文档中和 (2) 解析年季度,而不是年月。
【解决方案2】:

我们可以filter使用yearmonth函数在转换为Date类和ymd之后

library(tidyverse) 
df %>% 
   mutate(date = ymd(paste0(month, "-01"))) %>% 
   filter(year(date)>= 1942, month(date)>3, month(date)<=8, year(date) < 1943) %>%
   select(-date)

【讨论】:

  • 非常感谢!这就是我想要的!
  • 您也可以使用floor_date(date, "months") 来得到一个仍然像“1942-03-01”这样的真实日期。实际上,我发现这比执行zoo::yearmon(date) 然后转换回日期更有用。 floor_date() 还允许您将时间间隔调整为年、季度、月等。
猜你喜欢
  • 2012-12-18
  • 2010-09-22
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
相关资源
最近更新 更多