model.matrix错误:$运算符对原子向量无效

时间:2019-01-15 00:50:56

标签: r operator-keyword model.matrix

使用'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

是什么原因引起的问题?

1 个答案:

答案 0 :(得分:1)

检查?model.matrix。摘要:

     ## 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.

您的object是一个字符串公式,而datadata_Aobject自变量应为所述的公式或术语对象。试试

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

或等效地(如果您是根据字符串构造公式的话)

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