Using character as an object for linear model (R)

Viewed 203

I'm trying to test linear models with different interactions removed, e.g.

lmtest<-lm(out1~(.)^2 - var4:var5, data=dt1)

The interactions I'm testing for are stored in a character vector cvect = (var1:var2, var1:var3... etc), and I'm looking to use these to drop interactions. I've tried

lmtest<-lm(out1~(.)^2 - cvect[5], data=dt1)
lmtest<-lm(out1~(.)^2 - noquotes(cvect[5]), data=dt1)
lmtest<-lm(out1~(.)^2 - paste(cvect[5]), data=dt1)

But neither of these worked. Is there an alternative way of making this approach work?

3 Answers

I can never keep the formula-transforming functions straight so I usually build formulas as character strings. In your case:

# build formulas as characters
my_formula = paste("out1 ~ (.)^2 -", cvect)
# use like this:
lmtest(as.formula(my_formula[1]), data = dt1)

You could build the full model and then update minus each value of cvec in turn. The object mods has a new version of each model with one value of cvec removed.

set.seed(4391)
X <- matrix(rnorm(500), ncol=5)
colnames(X) <- paste0("X", 1:5)
b <- runif(5, -2,2)
yhat <- X %*% b
y <- yhat + rnorm(100, sd=2)
dat <- as.data.frame(X)
dat$y <- y
mod <- lm(y ~ (.)^2, data=dat)
cvec <- c("x1:x2", "x2:x3", "x3:x4")
mods <- lapply(cvec, function(z)
  update(mod, as.formula(paste0(". ~ . -", z))))

Here a reproducible example:

var_names <- names(iris)[-5]
model_list <- lapply(var_names,function(x) lm(paste0('Sepal.Length~Species:',x),data=iris))

You can achieve model outputs as model_list[[1]]

Related