tstools: The basics

Many years ago, when I started teaching an undergraduate forecasting class using R, I discovered that R had a ton of rough edges that made it hard to use R for basic time series analysis. I created a package called tstools holding various utilities designed to make time series analysis in R more convenient. Over time, I added additional functionality that made it suitable for use in my graduate courses, and it’s now something I (along with others) regularly use for research.

Unfortunately I have not had time to properly document the package. It’s something that you learn as you go if you take one of my econometrics classes. This is an overview of a few parts of the functionality (some of which does overlap with other packages, but that’s okay, since duplication reduces dependencies).

lags

There is a function called lag in base R. Unfortunately, it’s a bit of a nightmare for someone learning R:

  • lag(x,1) actually returns the lead of x, not the lag. lag(x,h) is translated into \(x_{t+h}\), so you have to instead call lag(x,-h) to get \(x_{t-h}\). That does the job, but the use of the name lag for that function doesn’t make any sense - and more importantly, it’s very easy to let a bug slip into your code.
  • lag can handle multiple variables (as an mts object) but not multiple lags. Thus, lag(x, 1:4) isn’t possible - and you’d really need lag(x, -(1:4)) to do what you want.

The function lags in tstools fixes both of these. First, it offers the more intuitive notation that lags(x,1) is \(x_{t-1}\). Second, you can do lags(x,1:4) to get the first four lags of x. In addition, it has an optional parameter type to specify if you want to group lags of multiple variables by variable or by lag. Suppose z holds variables x and y. lags(z, 1:3) will by default group all the lags of x together, followed by all the lags of y. lags(z, 1:3, type="byLag") orders the variables \(x_{t-1}\), \(y_{t-1}\), \(x_{t-2}\), \(y_{t-2}\), \(x_{t-3}\), \(y_{t-3}\). Which you prefer depends on the application. type="byLag" is often more useful when calculating a forecast.

make.trend


⤺ Back to the List of Computing Posts