user236260
user236260

Reputation: 51

R is not a matrix, but it won't take a data.frame either

I have been fighting this beast all day. On the one hand it wants a matrix, and on the other it wants a data.frame, and yet it will take neither. Please help.

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

Upvotes: 2

Views: 6647

Answers (2)

HiNoon
HiNoon

Reputation: 9

Coerce the object to a Data Frame using as.data.frame(x). In this case:

fdfdm <- as.data.frame(fdfdm)

That did the trick for me.

Upvotes: 0

www
www

Reputation: 4224

This error tends to occur when you're referencing objects/variables that are not columns in the data frame or matrix that you're using. So replacing "b + c + d + e" with the column names in your data should solve this. So try this:

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

If you'll be using all the columns in your data though, as appears to be the case here, then you can also use:

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

Upvotes: 1

Related Questions