2

I have a data set like this:

data <- ts(data.frame(a=c(104.8587, 104.5483, 104.0210, 105.7185,104.9054), 
           b=c(95.4, 95.9, 95.6, 95.5, 95.8)), start=c(2007,1), frequency=12)

> data
            a    b
Jan 2007 104.86 95.4
Feb 2007 104.55 95.9
Mar 2007 104.02 95.6
Apr 2007 105.72 95.5
May 2007 104.91 95.8

Now I want to ad the laged series of b to the data set. However, I'm struggleling, since whatever value I put in for k, it shows the same result.

> lag(data[,2], k=3)
      Jan  Feb  Mar  Apr  May
2007   NA 95.4 95.9 95.6 95.5

> lag(data[,2], k=5)
      Jan  Feb  Mar  Apr  May
2007   NA 95.4 95.9 95.6 95.5

I've already read the help page, but I couldn't find a hint beside that the laged series must be a time series object, which is fulfilled. So what am I doing wrong?

nelakell
  • 189
  • 2
  • 13

2 Answers2

3

If you open a new R session, it should work.

This is probably caused by having dplyr or another package loaded, and using lag from this rather than the base lag. dplyr lag uses n rather than k, explaining the problem:

#base lag

stats::lag(data[,2], k=3)

      Jan  Feb Mar Apr May Jun Jul Aug Sep  Oct  Nov  Dec
2006                                       95.4 95.9 95.6
2007 95.5 95.8  

#dplyr lag

dplyr::lag(data[,2], k=3)
      Jan  Feb  Mar  Apr  May
2007   NA 95.4 95.9 95.6 95.5

#correct dplyr lag

dplyr::lag(data[,2], n=3)
      Jan  Feb  Mar  Apr  May
2007   NA   NA   NA 95.4 95.9
jeremycg
  • 24,657
  • 5
  • 63
  • 74
0

Maybe you should try dplyr

library(dplyr)
data <- ts(data.frame(a=c(104.8587, 104.5483, 104.0210, 105.7185,104.9054), 
       b=c(95.4, 95.9, 95.6, 95.5, 95.8)), start=c(2007,1), frequency=12)
data.frame(data) %>% mutate(Lag = lag(b, n = 2))

You could also do:

dplyr::lag(data[,'b'], n = 2)
Teo
  • 67
  • 4