[R] extract variables from model formula
Joshua Wiley
jwiley.psych at gmail.com
Wed Aug 17 04:27:39 CEST 2011
Hi All,
I am writing a function to predict values based on a model. It works
fine as long as the formula just uses regular variable names. I am
having a problem when the variables are wrapped with a function call.
For example:
m <- lm(mpg ~ factor(cyl), data = mtcars)
## I get the column names using
as.character(attr(terms(m), "variables"))[-1L]
## which gives the same column names as in
# m$model
predict(m, m$model) # returns an error that 'cyl' is not found
Is there an easy way to get just the variable names or a template data
frame that I can populate with my own values from a model object? My
best idea right now is to use a regular expression to strip away
everything before and after (). This would break down for things like
I(cyl^2), though.
Any ideas or thoughts would be welcome.
Thanks,
Josh
--
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, ATS Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/
More information about the R-help
mailing list