Does lubridate have a similar function to yearmon at the zoo?

I am dealing with a data.frame with a month variable that only has a year and month component. Some of my data is as follows:

     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

      

I would like to convert the month variable to yearmon format for target use. My code looks like this:

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

      

I would like to know if the lubridate package has a similar function yearmon that could introduce a combination of year and month.

+3


source to share


2 answers


We can filter

use the function year

, month

after conversion into a class Date

withymd



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

      

+2


source


Here are the lubridate functions and the answer is no because it is lubridate

designed to work with dates and dates are days. You can assume day is 01 and convert to date format using ymd

or just stick with zoo::yearmon

.



+6


source







All Articles