Eric R.
2007-Nov-13 10:01 UTC
[R] a very easy question, how to extract the name of the response variable
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 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 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 > >-- View this message in context: http://www.nabble.com/a-very-easy-question%2C-how-to-extract-the-name-of-the-response-variable-tf4796264.html#a13722941 Sent from the R help mailing list archive at Nabble.com.
Prof Brian Ripley
2007-Nov-13 11:05 UTC
[R] a very easy question, how to extract the name of the response variable
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$formulaOh, 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 variableThat'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