2017-04-21 89 views
3

我正在处理一个只有年份和月份组件的月份变量data.frame。我的部分数据如下:lubridate是否具有与动物园的yearmon功能类似的功能?

 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 

我想将month变量转换为子日期格式,用于子目的。我的代码如下:

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

我想知道,如果lubridate封装具有相似的功能yearmon,可以采取年份和月份的组合输入。

+1

我只是修改我的代码,使之适用于例如 –

回答

2

我们可以通过yearmonth功能转换为Dateymd

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

非常感谢!这就是我要的! –

5

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

+1

或者使用任何时间:: anydate后filter(“1941年至1912年” ),这也假设日= 1 –

+0

如果是这样,你如何解释'yq()'函数...? –

+0

我将它解释为(1)隐藏在'ymd'文档中,(2)解析年度季度而不是年份。 – neilfws

相关问题