[R] extract variables from model formula

Joshua Wiley jwiley.psych at gmail.com
Wed Aug 17 17:31:27 CEST 2011


Hi Eik,

Thanks, that got me on the right track.  After looking at how
get_all_vars() works, I am using:

all.vars(as.formula(m))

which works great.

Thanks again,

Josh

On Wed, Aug 17, 2011 at 6:14 AM, Eik Vettorazzi
<E.Vettorazzi at uke.uni-hamburg.de> wrote:
> 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
>



-- 
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