rmodel.matrix

Error in model.frame.default(object, data, xlev = xlev) : variable lengths differ (found for 'z')


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?


Solution

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