0

This question has been asked before here and here, but without helpful answers for my problem. I have no missing data in my dataset and am trying to created a model.matrix from a model.frame. Here is an reproducible example:

dat = data.frame(x = rep(1:3, each = 5), 
    y = rnorm(15), 
    z = rep(c(1,1.1,1.3), each = 5))
# this works
mt = model.matrix(model.frame(lm(y ~ x,dat)))
# this produces the error
mt = model.matrix(model.frame(lm(y ~ x + z,dat)))

Why and how to fix this? Alternatively, how can I obtain a matrix of right-hand side values with the intercept column in another, yet effective and robust way?

nya
  • 2,138
  • 15
  • 29
  • 1
    `mt = model.matrix(model.frame(lm(y ~ x,dat)))` don't run. – cuttlefish44 Nov 24 '17 at 10:37
  • 1
    @cuttlefish44 is right, that line of code doesn't run as you've written it. That's because you need to look at `help("model.matrix")` to see which arguments the function expects; you need a formula or terms object as the first argument. Try `model.matrix(y ~ x + z, model.frame(lm(y ~ x + z, dat)))`. – duckmayr Nov 24 '17 at 11:38
  • 2
    `model.matrix` has default and lm methods. For the first write it as `model.matrix(y ~ x + z, dat)` or if you need to write it as a function of the `lm` object then `model.matrix(lm(y ~ x + z, dat))` – G. Grothendieck Nov 24 '17 at 13:10

1 Answers1

1

The problem is that model.matrix() expects a formula or terms object as the first argument. Solution:

model.matrix(y ~ x + z, model.frame(lm(y ~ x + z, dat)))
duckmayr
  • 16,303
  • 3
  • 35
  • 53