[R] getting variable names from formula
Dimitris Rizopoulos
dimitris.rizopoulos at med.kuleuven.ac.be
Wed Jan 12 10:56:43 CET 2005
maybe something like:
f <- y ~ x1 + x2
attr(terms(f), "term.labels")
but this wan't work if you have a more complex formula (e.g., f <- y ~
x1*x2 + I(x1^2)) and you want only c("x1", "x2").
I hope it helps.
Best,
Dimitris
----
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven
Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/16/336899
Fax: +32/16/337015
Web: http://www.med.kuleuven.ac.be/biostat
http://www.student.kuleuven.ac.be/~m0390867/dimitris.htm
----- Original Message -----
From: "Daniel Almirall" <dalmiral at umich.edu>
To: <r-help at stat.math.ethz.ch>
Sent: Tuesday, January 11, 2005 9:55 PM
Subject: [R] getting variable names from formula
> R-list,
>
> 1. Given a formula (f) w variables referencing some data set (dat),
> is
> there any easier/faster way than this to get the names (in character
> form)
> of the variables on the RHS of '~' ?
>
> dat <- data.frame(x1 = x1 <- rnorm(100,0,1), x2 = x2 <-
> rnorm(100,0,1), y = x1 + x2 + rnorm(100,0,1))
>
> f <- y ~ x1 + x2
>
> mf <- model.frame(f, data=dat)
>
> mt <- attr(mf, "terms")
>
> predvarnames <- attr(mt, "term.labels")
>
>> predvarnames
> [1] "x1" "x2"
>
> -----
>
> 2. Also, is there an easy/fast way to do it, without having the
> data set
> (dat) available? That is, not using 'model.frame' which requires
> 'data'?
> I understand that one approach for this is to use the way formulas
> are
> stored as 'list's. For example, this works
>
> predvarnames <- character()
>
> for (i in 2:length(f[[3]]) ){
>
> predvarnames <- c(predvarnames, as.character(f[[3]][[i]]))
>
> }
>
>> predvarnames
> [1] "x1" "x2"
>
> but is there a better way?
>
> Thanks,
> Danny
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>
More information about the R-help
mailing list