[R] How to specify a variable name in the regression formula without hard coding it

Jean-Christophe BOUËTTÉ jcbouette at gmail.com
Thu Sep 8 15:21:37 CEST 2011


have a look at ?formula and the examples

2011/9/8 Bos, Roger <roger.bos at rothschild.com>:
> I have a matrix called mat and y is the column number of my response and
> x is a vector of the column numbers of my terms.  The variable name of y
> can change, so I don't want to hardcode it.  I can find out the name as
> follows:
>
>>            names(mat)[y]
> [1] "er12.l"
>
> Then I can run the regression by hard coding the variable name as
> follows:
>
>>             mod <- try(rlm(er12.l ~ ., data=mat[zidx, c(y, x)]),
> silent=TRUE)
>
> But how would I do so without hard coding the name er12.l?
>
> I set up a reproducible example.  In the following my regression formula
> is aa ~ bb + cc, or more simply aa ~ .
> How can I use the name of the first column without hard coding aa?
>
> dat <- data.frame(aa=runif(50), bb=runif(50), cc=runif(50))
> names(dat)[1]
> lm(aa ~ ., data=dat[1:10,])
>
> Thanks,
>
> Roger
> ***************************************************************
>
> This message is for the named person's use only. It may\...{{dropped:14}}
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list