[R] getting variable names from formula

Daniel Almirall dalmiral at umich.edu
Tue Jan 11 21:55:27 CET 2005


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




More information about the R-help mailing list