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 = "+"))'