[R] lags of a variable, with a factor

Jim Lemon jim at bitwrit.com.au
Mon Aug 26 02:12:04 CEST 2013


On 08/24/2013 08:25 PM, Jim Lemon wrote:
 > ...
Oops, very bad editing of the function in the email - this should work:

lags <- function(x, k=1, prefix='lag', by) {
  if(missing(by)) {
   n <- length(x)
   res <- data.frame(lag0=x)
   for (i in 1:k) {
     res <- cbind(res, c(rep(NA, i), x[1:(n-i)]))
   }
   colnames(res) <- paste0(prefix, 0:k)
  }
  else {
   for(levl in levels(by)) {
    nextlags<-lags(x[by==levl],prefix=prefix)
    rownames(nextlags)<-paste(levl,rownames(nextlags),sep=".")
    if(exists("res")) res<-rbind(res,nextlags)
    else res<-nextlags
   }
  }
  return(res)
}

Also make sure that "by" _is_ a factor. It doesn't work if it isn't.

Jim



More information about the R-help mailing list