[R] getting variable names from formula
Douglas Bates
bates at wisc.edu
Wed Jan 12 10:32:59 CET 2005
Daniel Almirall wrote:
> 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
That's exactly what the all.vars function does. If you apply it to the
formula you get all the names of variables referenced in the formula.
If you only want the right hand side then apply it to the third
component of the formula
> f <- y ~ x1 + x2
> all.vars(f)
[1] "y" "x1" "x2"
> all.vars(f[[3]])
[1] "x1" "x2"
More information about the R-help
mailing list