Help with lag date in R

Hello everybody,

I would like to ask for help.
For example, I would like to change (year and month) from 2010_7 to 2010_01. It means I want to change (lag) 6 months. I used the lag function but it creates NA value. I would like to have a new variable "yearmm_new" like the picture below. I appreciate any helps.
Thank you in advance. My data is like that.


yearmm = c(20107L,20108L,20109L,201010L,201011L,


year = c(2010L,2010L,2010L,2010L,2010L,2010L,


mm = c(7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L),

price = c(12666L,19596L,14223L,8357L,9188L,8591L,


stock = as.factor(c("AAA","AAA","AAA",


date = as.factor(c("2010-07-30",





       date_m6 = ymd(date) %m+% - months(6),
       yearmm_new = year(date_m6)*100+month(date_m6))
1 Like

Thank you so much for your help.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.