代码之家  ›  专栏  ›  技术社区  ›  LeGeniusII

model.matrix错误:$operator对于原子向量无效

  •  0
  • LeGeniusII  · 技术社区  · 6 年前

    我在使用'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 回复  |  直到 6 年前
        1
  •  1
  •   mathematical.coffee    6 年前

    检查 ?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 . 这个 对象 如前所述,参数应为公式或术语对象。尝试

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

    或等效(如果是从字符串构造公式)

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