使用'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
是什么原因引起的问题?
答案 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
是一个字符串公式,而data
是data_A
。 object
自变量应为所述的公式或术语对象。试试
model.matrix(Y ~ X1 + X2, data_A)
或等效地(如果您是根据字符串构造公式的话)
model.matrix(as.formula(Y ~ X1 + X2), data_A)