Birdonawire
Birdonawire

Reputation: 319

Showing variable names for model summary when using a call

I have a loop for running several models

library(MuMIn)
options(na.action = "na.fail")
dat = iris
listX = names(iris[,3:4]
listY = names(iris[,1:2]

for (y in listY){

fm1 <- lm(dat[[y]] ~ dat[[listX[1]]] + dat[[listX[2]]], data=dat)
dd = dredge(fm1)
print(dd)
}

When I run this, the output of print(dd) shows the variable names as given such as dat[[listX[2]]] etc.

How can I change the code so that I can see the actual names of the variables in the model as if I had written the full variables names for each loop e.g.

 fm1 <- lm(Sepal.length ~ Petal.Length + Petal.Width, data=dat)

Upvotes: 0

Views: 395

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

Just compose the formula in the for loop using paste.

for (y in listY){
    fmla <- as.formula(paste(y, paste(listX[1], listX[2], sep = "+"), sep = "~"))
    fm1 <- lm(fmla, data=dat, na.action = na.pass)
    dd = dredge(fm1)
    print(dd)
}

Notes:

  1. You should have started your example with a call to library, dredge is not a base R package, it's in package MuMIn.
  2. The code as you've posted throws an error, I had to use na.action = na.pass in the call to lm for dredge to execute.

EDIT.
As lmo noted in the comment, reformulate is much simpler and readable than nested paste instructions. The loop would then become:

for (y in listY){
    fmla <- reformulate(listX, y)
    fm1 <- lm(fmla, data=dat, na.action = na.pass)
    dd = dredge(fm1)
    print(dd)
}

Upvotes: 1

Related Questions