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

David Winsemius dwinsemius at comcast.net
Thu Sep 8 15:21:25 CEST 2011


On Sep 8, 2011, at 9:03 AM, Bos, Roger wrote:

> 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))

"dep <- names(dat)[1]; indep <- names(dat)[2]

> lm(aa ~ ., data=dat[1:10, c(dep,indep])
>


 > dep <- names(dat)[1]; indep <- names(dat)[2]
 > lm(aa ~ ., data=dat[1:10, c(dep,indep)])

Call:
lm(formula = aa ~ ., data = dat[1:10, c(dep, indep)])

Coefficients:
(Intercept)           bb
     0.58908      0.03389


> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list