roperator-keywordmodel.matrix

model.matrix Error: $ operator is invalid for atomic vectors


I ran into this error when using 'model.matrix'.

data_A <- data.frame(X1 = c("Y","N"), X2 = c(20,24), Y = c("N","Y"))
data_A
model.matrix("Y ~ X1 + X2", data_A)
Error: $ operator is invalid for atomic vectors

What's causing the problem?


Solution

  • Examine ?model.matrix. A snippet:

         ## Default S3 method:
         model.matrix(object, data = environment(object),
                      contrasts.arg = NULL, xlev = NULL, ...)
    
    Arguments:
    
      object: an object of an appropriate class.  For the default method, a
              model formula or a ‘terms’ object.
    

    Your object is a string formula while data is data_A. The object argument should be a formula or terms object as stated. Try

    model.matrix(Y ~ X1 + X2, data_A)
    

    or equivalently (if you are constructing the formula from a string)

    model.matrix(as.formula(Y ~ X1 + X2), data_A)