Wednesday, July 29, 2009

Using formulas in your own code

The next four lines of code allow you to create your vector y (dependent variable) and matrix X of explanatory variables from a formula and a data.frame.

#creation of an object of class "terms" decomposing the formula into a usable form
trm <- terms(formula,data=data)

#creation of a model.frame i.e. a data.frame corresponding to the formula
modelfrm <- lm(formula,data,method="model.frame")

#extraction of the dependent variable
y <- model.extract(modelfrm,"response")

#extraction of the independent variables
X <- model.matrix(trm,modelfrm)

No comments:

Post a Comment