简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM