Michael Ash
2011-Jun-18 10:24 UTC
[R] Unexpected result with lag() et diff() in plm package.
I have an unexpected result with the functions lag() and diff() in the plm (panel data) package when used with transform(). These plm-specific functions are supposed to generate lags and first differences within each panel. lag() does not work properly the first time (it reproduces the same series--this is a common time series pitfall), BUT then it does work properly when it is run a second time. (This is demonstrated in the code below. diff() does not work at all if it is run before lag(). It works properly if it is run after lag(). The problem occurs only inside a transform statement. lag() and diff() work correctly with Grunfeld.p$l.value <- lag(Grunfeld.p$value,1) Grunfeld.p$d.value <- diff(Grunfeld.p$value,1) Here is code to reproduce the error: library(plm) data(Grunfeld) Grunfeld.p <- pdata.frame(Grunfeld,c("firm","year")) Grunfeld.p <- transform(Grunfeld.p, l.value = lag(value,1)) head(Grunfeld.p) Grunfeld.p <- transform(Grunfeld.p, l.value = lag(value,1)) head(Grunfeld.p) Run the following in a separate R session: library(plm) data(Grunfeld) Grunfeld.p <- pdata.frame(Grunfeld,c("firm","year")) Grunfeld.p <- transform(Grunfeld.p, d.value = diff(value,1)) head(Grunfeld.p) Grunfeld.p <- transform(Grunfeld.p, l.value = lag(value,1)) Grunfeld.p <- transform(Grunfeld.p, d.value = diff(value,1)) head(Grunfeld.p) R version 2.13.0 (2011-04-13) Platform: i686-pc-linux-gnu (32-bit) other attached packages: [1] plm_1.2-6 sandwich_2.2-6 zoo_1.6-4 MASS_7.3-13 [5] Formula_1.0-0 kinship_1.1.0-23 lattice_0.19-26 nlme_3.1-101 [9] survival_2.36-9 Information on package 'plm' Description: Package: plm Version: 1.2-6 Date: 2010-11-20 Title: Linear Models for Panel Data -- Michael Ash, Associate Professor of Economics and Public Policy Department of Economics and CPPA University of Massachusetts Amherst, MA 01003 Email mash@econs.umass.edu Tel +1-413-545-6329 // Fax +1-413-545-2921 http://people.umass.edu/maash -- Michael Ash, Associate Professor of Economics and Public Policy Department of Economics and CPPA University of Massachusetts Amherst, MA 01003 Email mash@econs.umass.edu Tel +1-413-545-6329 // Fax +1-413-545-2921 http://people.umass.edu/maash [[alternative HTML version deleted]]