[R] a very easy question, how to extract the name of the response variable

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Nov 13 12:05:46 CET 2007


On Tue, 13 Nov 2007, Eric R. wrote:

>
> This may not be the smoothest way to produce the result, but here is a
> two-step solution:
>
> first find the formula within the object created by the call to glm():
>
> form <- qq["formula"] or equivalently form <- qq$formula

Oh, please , do use extractors where provided,

> then apply the function all.vars() to the result, and return the first
> element
>
> variables.in.formula <- all.vars(form)
>
> variables.in.formula[1]  #  will be the response variable

That's not guaranteed by any means.  The response could be an expression, 
not a variable.  A fairly simple way is

formula(qq)[[2]]

which will produce a language object such as a name.  If you want a 
character string you can then use either deparse() or as.character() on 
it.  So something like

ff <- function(fit)
{
     f <- formula(fit)
     if(length(f) < 3) stop("no response")
     resp <- f[[2]]
     if(!is.name(resp)) stop("response is not a name")
     as.character(resp)
}


> leffgh wrote:
>>
>> for example
>> glm(a~b+c+d,data=eee)->qq
>>
>> Is there a function able to return the name of the response variable?
>> suppose "ff" is the function satisfying this need,
>> ff(qq) then "a" (Not the value of a) will be returned.
>> could you tell me which is the "ff" I am looking for ?
>>
>> Thank you very much

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list