[R] extract variables from model formula

Eik Vettorazzi E.Vettorazzi at uke.uni-hamburg.de
Wed Aug 17 15:14:05 CEST 2011


Hi Josh,
I think,

m <- lm(mpg ~ factor(cyl)+I(mpg^2), data = mtcars)
nd<-get_all_vars(m,data=mtcars)

is what you are after.

cheers.

Am 17.08.2011 04:27, schrieb Joshua Wiley:
> 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
> 
> 

-- 
Eik Vettorazzi
Institut für Medizinische Biometrie und Epidemiologie
Universitätsklinikum Hamburg-Eppendorf

Martinistr. 52
20246 Hamburg

T ++49/40/7410-58243
F ++49/40/7410-57790



More information about the R-help mailing list