Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 507
LeGeniusII Avatar asked Jan 22 '26 23:01

LeGeniusII


1 Answers

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)
like image 101
mathematical.coffee Avatar answered Jan 24 '26 16:01

mathematical.coffee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!