[R] converting to a language object

kjetil brinchmann halvorsen kjetil at entelnet.bo
Sat Feb 8 14:06:03 CET 2003


On 8 Feb 2003 at 2:13, Arnab mukherji wrote:

> Hi,
> 
> I have a query about the following:
> 
> CONTEXT:
> if we define:
> 
> eq <- y ~ x1 + x2
> 
> then is.language(eq) returns true.
> this works perfectly with commands such as
> lm(eq,data=my.data)
> 
> THE PROBLEM:
> Now I have a big data set with about 2000 independent variables. So I tried to automate this. I can pick off the names of the variables and insert a plus in between them and get a string. Thus I have 
> 
> eq<- y ~ " x1 + x2 + ... +x2000"
> or
> eq<-"y ~ " x1 + x2 + ... +x2000"
> 
> from either case how can I typecast eq into a langugae object and get the lm command to work ?
> 
> Does anyone have any suggestions?
> 
What about the following:

> sum <- paste("+ x", 1:5, sep="", collapse="")
> sum
[1] "+ x1+ x2+ x3+ x4+ x5"
> sum <- substr(sum,2,20)
> sum
[1] " x1+ x2+ x3+ x4+ x5"
> formula <- as.formula(paste("y ~ ", sum, sep="", collapse=""))
> formula
y ~ x1 + x2 + x3 + x4 + x5
> class(formula)
[1] "formula"
> # simulating some random data
> lm(formula)

Call:
lm(formula = formula)

Coefficients:
(Intercept)           x1           x2           x3           x4       
    x5  
    0.05959      0.07876      0.20845     -0.11539     -0.14293     -
0.11421 

Kjetil Halvorsen


> thanks
> 
> Arnab.
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> http://www.stat.math.ethz.ch/mailman/listinfo/r-help




More information about the R-help mailing list