3

Can the effects package in R be used to plot (marginal) effects for a linear model which does not include an intercept?

Here is some R code I tried for such a model:

x <- seq(1,100,by=0.1)
y <- 1 + 2*x + rnorm(n=length(x))

model <- lm(y ~ 0 + x)

require(effects)
plot(allEffects(model))

The error it produces is as follows:

Error in plot(allEffects(model)) : 
error in evaluating the argument 'x' in selecting a method for function 'plot': 
Error in   mod.matrix %*% mod$coefficients[!is.na(mod$coefficients)] : 
non-conformable arguments

If anyone has any ideas for how to overcome this error, please let me know.

Thanks,

Isabella

jay.sf
  • 60,139
  • 8
  • 53
  • 110
Isabella Ghement
  • 715
  • 6
  • 14

1 Answers1

3

There sure does appear to be a bug in the code. In particular, with dispatching, the allEffects code calls effect which calls Effect.lm. This particular is recreated also with

Effect.lm("x", mod=model)
# Error in mod.matrix %*% mod$coefficients[!is.na(mod$coefficients)] : 
#   non-conformable arguments

The error appears to come from line 30 of body of this function

body(effects:::Effect.lm)[[30]]
# mod.matrix <- mod.matrix[, !is.na(mod$coefficients)]

The problem occurs when you only have 1 non-NA coefficient (as you would with a single regressor and no intercept). The problem is that when you do this subset on a single column, the result is automatically don't cast to a vector rather than a matrix. We can create our own version of the function that fixes this problem

my.Effect.lm<-effects:::Effect.lm
body(my.Effect.lm)[[30]] <- quote(mod.matrix <- mod.matrix[, !is.na(mod$coefficients), drop=FALSE])
environment(my.Effect.lm) <- asNamespace("effects")

Then

model <- lm(y ~ 0 + x)
plot(my.Effect.lm("x", model))

should work. I must admit i haven't figured out how to get allEffects to work. I can't remember how to change how the S3 dispatch works when it resolved functions in different namespaces. There doesn't seem to be any easy way to fix the function that's actually located in the effects namespace.

So in general the function should work without intercepts as long as you have more than one regressor. You may want to contact the package author to report this problem.

MrFlick
  • 195,160
  • 17
  • 277
  • 295