[R] lags of a variable, with a factor

Michael Friendly friendly at yorku.ca
Mon Aug 26 15:44:39 CEST 2013


On 8/25/2013 8:12 PM, Jim Lemon wrote:
> 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)
> }

Thanks for trying again, but that doesn't work either with a by= 
variable. Note that your function is recursive, and also k=k
should be passed in the else{ ... lags() }.

 > events <- sample(letters[1:4], 10, replace=TRUE)
 > lags(events)
    lag0 lag1
1     c <NA>
2     b    c
3     d    b
4     d    d
5     b    d
6     b    b
7     b    b
8     c    b
9     a    c
10    a    a
 > lags(events, 3)
    lag0 lag1 lag2 lag3
1     c <NA> <NA> <NA>
2     b    c <NA> <NA>
3     d    b    c <NA>
4     d    d    b    c
5     b    d    d    b
6     b    b    d    d
7     b    b    b    d
8     c    b    b    b
9     a    c    b    b
10    a    a    c    b
 >
 > events2 <- data.frame(sub=factor(rep(1:2, each=5)),
+                       event=sample(letters[1:4], 10, replace=TRUE),
+                       stringsAsFactors=FALSE)
 > events2
    sub event
1    1     b
2    1     c
3    1     a
4    1     a
5    1     b
6    2     a
7    2     b
8    2     a
9    2     b
10   2     a
 > lags(events2, 2, by=sub)
Error in lags(events2, 2, by = sub) : object 'res' not found
 > lags(events2, by=sub)
Error in lags(events2, by = sub) : object 'res' not found

-Michael

-- 
Michael Friendly     Email: friendly AT yorku DOT ca
Professor, Psychology Dept. & Chair, Quantitative Methods
York University      Voice: 416 736-2100 x66249 Fax: 416 736-5814
4700 Keele Street    Web:   http://www.datavis.ca
Toronto, ONT  M3J 1P3 CANADA



More information about the R-help mailing list