# Problem with character vectors and linear regression in R

Quick question.

I want to perform a linear regression that looks like this:

lm(y ~ x1 + x2 + x3 + x4 +x5, mydata)


This works fine if I manually write out this code.

However, the independent variables that I want to use are stored as a character, like this:

> vars
[1] "x1 + x2 + x3 + x4 +x5"


I tried typing this:

lm(y ~ vars, mydata)
Error in model.frame.default...


But it gives an error!

So then I tried this:

lm(y ~ noquote(vars), mydata)
Error in model.frame.default...


And then this

lm(y ~ print(vars, quote = FALSE), mydata)
Error in model.frame.default...


Anyone have a clue how I can get around this problem? The character string in "vars" is being provided to me by a program upstream, so I can't work around it at that level.

Thanks!

-
Don't you have access to x1,...,x5? I do not get this "x1+...+x5" representation. – Xi'an Feb 1 '12 at 21:53
Yes, but I just put them there as placeholders as an example. They are just variables. I have thousands of variables in my database, so writing this code by hand is not possible. – Alexander Feb 1 '12 at 21:56
@Xi'an Alexander has a character string representing the RHS of a model formula in R. The problem then is how to create a valid R formula from this character string representation. – Gavin Simpson Feb 1 '12 at 21:57
+1 From me - clear question with simple example and evidence of effort in trying to solve the problem. Not sure why this was down-voted? – Gavin Simpson Feb 1 '12 at 21:58

You can build a formula from character vectors using standard R functions and as.formula(). The trick is to note that you need to have a full formula (containing at least a ~) for R to create a formula object for you. Here is an example

## predictors
vars <- "x1 + x2 + x3 + x4 + x5"

## dummy data for example
dat <- data.frame(matrix(rnorm(120), ncol = 6))
names(dat) <- c("y", paste("x", 1:5, sep = ""))

## create a formula - here we need to paste on the response part
##  y ~
form <- as.formula(paste("y ~", vars))

## Fit the model using form
mod <- lm(form, data = dat)


If you print form you'll see that R has created a special object that no longer prints as a character string would:

> form
y ~ x1 + x2 + x3 + x4 + x5

-
 Gavin, thanks a ton for your help! This is the first time that I've come across the "as.formula()" function - quite useful! – Alexander Feb 1 '12 at 22:04