0

I'm having problems with predicting a raster using a linear model.

Firstly i create my model from the data found in my polygons.

  # create model
  poly <- st_read("polygon.shp")
  df <- na.omit(poly)
  df <- df[df$gdp > 0 & df$ntl2 > 0 & df$pop2 > 0,]

  x <- log(df$ntl2)
  y <- log(df$gdp*df$pop2)
  c <- df$iso
  d <- data.frame(x,y,c)

  m <- lm(y~x+c,data=d)

Then i want to use raster::predict to estimate an output raster

  # raster data
  iso <- raster("iso.tif")
  viirs <- raster("viirs.tif")

  x <- log(viirs)
  c <- iso

  ## predict with models
  s <- stack(x,c)
  predicted <- raster::predict(x,model=m)

however i get following response:

Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : 
  object is not a matrix

I don't know what the problem is and how to fix it. My current throughts are that its something to do with the factors/country codes:

My model includes country codes, as I would like to include some country fixed effects. Maybe there is a problems with including these. However even when excluding the country codes from the model and the entire dataframe, i still get the same error message.

Futhermore, my model is based on regional values from the whole world and the prediction datasets only include the extent of Turkey. Maybe this is the problem?

And here is the data: https://drive.google.com/open?id=16cy7CJFrxQCTLhx-hXDNHJz8ej3vTEED

minium
  • 43
  • 5
  • Try to test the structures of your train/test data with str(data) to see if they have the same format. – Esben Eickhardt Apr 30 '19 at 10:08
  • The training data is a dataframe with x and y values, and the test data is a raster of x values. Apart from that i cannot see any differences, although i dont know what i should be looking for. – minium Apr 30 '19 at 15:01
  • You should look for types of data: Are both train and test matrices? Are the x-values numerical in both train and test? – Esben Eickhardt Apr 30 '19 at 15:04
  • please provide a simple, reproducible example that comes with its own data. See e.g. ?raster::predict about how to make one. The error seems to be that `x` is not what you want to use in `predict`. – Robert Hijmans Apr 30 '19 at 15:19

1 Answers1

0

Perhaps it works if you do like this:

iso <- raster("iso.tif")
viirs <- raster("viirs.tif")
s <- stack(log(viirs), iso)
names(s) <- c("x", "c")

predicted <- raster::predict(s, model=m)
  

It won't work if the values in df$iso and iso.tif don't match (is one a factor, and the other numeric?).

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63