[R] Extract lags from a formula

hadley wickham h.wickham at gmail.com
Fri May 2 20:42:55 CEST 2008


On Fri, May 2, 2008 at 1:35 PM, Kerpel, John <John.Kerpel at infores.com> wrote:
> Hi folks!
>
>
>
>  How do I extract lags from a formula?  An example:
>
>
>
>  mod.eq<-formula(x~lag(x,-1)+lag(x,-2))
>
>  > mod.eq
>
>  x ~ lag(x, -1) + lag(x, -2)
>
>  > mod.eq[1]
>
>  "~"()
>
>  > mod.eq[2]
>
>  x()
>
>  > mod.eq[3]
>
>  lag(x, -1) + lag(x, -2)()
>
>
>
>  I'm trying to extract the lags into a vector that would be simply [1,2].
>  How do I do this?  I'm using the dyn package to do dynamic regression.

Maybe something like:

f <- formula(x~lag(x,-1)+lag(x,-2))

lags <- function(x) {
  if (length(x) != 3) return()

  if (x[[1]] == as.name("lag")) {
    return(eval(x[[3]]))
  } else {
    return(c(lags(x[[2]]), lags(x[[3]])))
  }
}

R expressions are preorder trees.

Hadley

-- 
http://had.co.nz/



More information about the R-help mailing list