Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Problems with raster prediction from linear model in r

Writer Olivia Zamora

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:

4

1 Answer

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?).

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.