Re: [R] Extract lags from a formula

From: hadley wickham <h.wickham_at_gmail.com>
Date: Fri, 02 May 2008 13:42:55 -0500

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/

______________________________________________
R-help_at_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.
Received on Fri 02 May 2008 - 19:11:44 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 02 May 2008 - 19:30:33 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive