Search code examples
rvectorlinear-regression

Using character as an object for linear model (R)


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?


Solution

  • 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)