Data:
mtcars
I make a model:
lm(formula = mpg ~., data = mtcars)
By another algorithm I get this:
"disp+hp+drat+wt+qsec" -> lista
If I put it in the model it works:
lm(formula = mpg ~disp+hp+drat+wt+qsec, data = mtcars)
But if I put it like this it doesn't work:
lm(formula = mpg ~lista, data = mtcars)
I have tried to transform it with all the aces.
as.character(lista) -> lista
as.array(lista) -> lista
etc
but the model does not pick it up.
You can transform the characters to type "formula" (language object) using
as.formula()
orformula()
.With the help of the function
paste()
you can concatenate the characters as follows:You can then apply the function
lm()
to that object:Your case seems simple, in fact a quick answer could be that you use
as.formula()
to convert a string that represents a formula into a formula itself, the point is that the string must be consistent with a formula, so in any case you should do something So:However, there is a detail that you raise that is interesting to comment on, although it is an advanced topic. In your case, you want to combine a symbolic expression
mpg
with a string expression to finish building the formula. Are you looking to do something like this:Beyond the fact that there is a function
convertir_a_expresión_simbolica()
in R, there is another problem: the function~
that actually builds the formula is totally literal with the parameters it receives, and in this contextconvertir_a_expresión_simbolica(cadena)
it will always be a function that converts to an expression but not an expression in Yes.We could, as an alternative, make a new function
~
that receives a symbol (mpg
) and a string and always returns a valid formula:In the example it
substitute(o)
replaces the symbolo
for which parameter was passedmpg
, everything is concatenated in a string and it is evaluated and returned as a formula.