1

I am trying to build an R shiny application where I have the user select variables for a model. The elements that the user selects get put into a vector. How do I remove the quotes as well as put spaces between each element they select, to be variables in a model?

As an example:

> vars <- c("cyl", "disp", "hp")
> my.model <- lm(mpg ~ paste(vars, collapse = "+"), data = mtcars)

Gives the error:

Error in model.frame.default(formula = mpg ~ paste(vars, collapse = "+"),  :
variable lengths differ (found for 'paste(vars, collapse = "+")')

From reading other somewhat similar questions on Stackoverflow, someone suggested to use as.name() to remove the quotation marks, but this produces another error:

> vars <- c("cyl", "disp", "hp")
> my.model <- lm(mpg ~ as.name(paste(vars, collapse = "+")), data = mtcars)
Error in model.frame.default(formula = mpg ~ as.name(paste(vars, collapse = "+")),  :
invalid type (symbol) for variable 'as.name(paste(vars, collapse = "+"))'
MrFlick
  • 163,738
  • 12
  • 226
  • 242

2 Answers2

2

A formula is not just a string without quotes. It's a collection of un-evaluated symbols. Try using the build in reformulate function to build your formula.

vars <- c("cyl", "disp", "hp")
my.model <- lm(reformulate(vars,"mpg"), data = mtcars)
MrFlick
  • 163,738
  • 12
  • 226
  • 242
2

as.formula should be able to coerce strings into formula

lm(as.formula((paste("mpg ~", paste(vars, collapse = "+")))), data = mtcars)

#Call:
#lm(formula = as.formula((paste("mpg ~", paste(vars, collapse = "+")))), 
#    data = mtcars)

#Coefficients:
#(Intercept)          cyl         disp           hp  
#   34.18492     -1.22742     -0.01884     -0.01468  
d.b
  • 29,772
  • 5
  • 24
  • 63