Rob
Rob

Reputation: 395

How do I use paste and as.formula to generate a complex formula?

I am attempting to input an equation using R in a loop, and so I am using as.formula and paste. The end result should be:

library(nlme)
glm(Sepal.Length ~ Sepal.Width + Petal.Length +Petal.Width, 
  family = gaussian(),data=iris)

Whether or not this is the right model, don't worry, its just an example. I have these variables broken up into 3 components

Why is this not working?

library(nlme)

glmi = glm(as.formula(paste("Sepal.Length ~ Sepal.Width+ ", 
           paste('Petal.Length +Petal.Width',
           paste(',', 'family = gaussian(),data=iris')))))

Upvotes: 0

Views: 1306

Answers (1)

Hobo
Hobo

Reputation: 7611

The formula argument of glm() is only this bit:

Sepal.Length ~ Sepal.Width + Petal.Length +Petal.Width

of your original code - family = gaussian(), data=iris are different glm() arguments, and don't belong in there.

Based on what you have, something like

glm(
  as.formula(paste("Sepal.Length ~ Sepal.Width+ ", paste('Petal.Length +Petal.Width'))),
  family = gaussian(),
  data=iris
)

would seem to be the equivalent of what you're trying.

I've left the unnecessary second paste() in there as presumably it corresponds to more complex logic that you've simplified for the question.

Upvotes: 2

Related Questions