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

Bos, Roger roger.bos at rothschild.com
Thu Sep 8 15:29:10 CEST 2011


The answer to my question was :

fmla <- as.formula(names(mat)[y] %+% " ~ .")
mod <- try(rlm(fmla, data=mat[zidx, c(y, x)]), silent=TRUE) 

Thanks for your help and the quick response.

Roger

-----Original Message-----
From: Jean-Christophe BOUËTTÉ [mailto:jcbouette at gmail.com] 
Sent: Thursday, September 08, 2011 9:22 AM
To: Bos, Roger
Cc: r-help at r-project.org
Subject: Re: [R] How to specify a variable name in the regression formula without hard coding it

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 ...{{dropped:26}}



More information about the R-help mailing list