【问题标题】:R is not a matrix, but it won't take a data.frame eitherR 不是矩阵,但也不需要 data.frame
【发布时间】:2017-09-11 00:19:34
【问题描述】:

我整天都在和这只野兽战斗。一方面它想要一个矩阵,另一方面它想要一个 data.frame,但它都不需要。请帮忙。

> Coffee <- raster("b2boolcafetst.rst")
> b <- raster("b2_dstcabtst.rst")
> c <- raster("b2_dstrdstst.rst")
> d <- raster("b2_dstfuentst.rst")
> e <- raster("b2_srtmtst.rst")
> fdf <- as.data.frame(stack(Coffee, b, c, d, e))
> str(fdf)
'data.frame':   296856 obs. of  5 variables:
 $ b2boolcafetst: num  0 0 0 0 0 0 0 0 0 0 ...
 $ b2_dstcabtst : num  9512 9482 9452 9422 9392 ...
 $ b2_dstrdstst : num  1980 1980 1981 1982 1984 ...
 $ b2_dstfuentst: num  5155 5134 5112 5091 5070 ...
 $ b2_srtmtst   : num  975 980 984 991 998 ...
> fdfdm <- as.matrix(fdf)
> str(fdfdm)
 num [1:296856, 1:5] 0 0 0 0 0 0 0 0 0 0 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:5] "b2boolcafetst" "b2_dstcabtst" "b2_dstrdstst" "b2_dstfuentst" ...
> fdfmod <- glm(Coffee ~ b + c + d + e, family=binomial(link='logit'), 
+              data=fdf)
Error in model.frame.default(formula = Coffee ~ b + c + d + e, data = fdf,  : 
  object is not a matrix
> fdfmod <- glm(Coffee ~ b + c + d + e, family=binomial(link='logit'), 
+              data=fdfdm)
Error in model.frame.default(formula = Coffee ~ b + c + d + e, data = fdfdm,  : 
  'data' must be a data.frame, not a matrix or an array
> 

【问题讨论】:

  • Coffee ~ b + c + d + e替换为对应的名称b2boolcafetstb2__dstcabtst

标签: r dataframe r-raster


【解决方案1】:

当您引用不是您正在使用的数据框或矩阵中的列的对象/变量时,往往会发生此错误。因此,用数据中的列名替换“b + c + d + e”应该可以解决这个问题。所以试试这个:

glm(Coffee ~ b2_dstcabtst + b2_dstrdstst + b2_dstfuentst + b2_srtmtst, 
    family=binomial(link='logit'), data=fdf)

如果您将使用数据中的所有列,就像这里的情况一样,那么您也可以使用:

glm(Coffee ~ ., family=binomial(link='logit'), data=fdf)

【讨论】:

  • 我永远猜不到这个解决方案,但它奏效了;对于那些好奇的人,它可以作为 data.frame 的解决方案,而不是矩阵的解决方案。非常感谢!彼得
  • @user236260 - 没问题,很高兴我能帮上忙。请选择此作为解决方案,以帮助将来有相同问题的其他人更快地找到答案。
【解决方案2】:

使用as.data.frame(x) 将对象强制转换为数据框。在这种情况下:

fdfdm <- as.data.frame(fdfdm)

这对我有用。

【讨论】:

    猜你喜欢
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多