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.

data<-data.frame(

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

201012L,20111L,20112L,20113L,20114L),

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

2011L,2011L,2011L,2011L),

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

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

9058L,7371L,6515L,5736L),

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

"AAA","AAA","AAA","AAA","AAA","AAA","AAA")),

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

"2010-08-31","2010-09-30","2010-10-29","2010-11-30",

"2010-12-31","2011-01-28","2011-02-28","2011-03-31",

"2011-04-29"))

)

mutate(data,
       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.