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 ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.