How to fix the problem the error number of items to replace is not a multiple of replacement length in R?

757 views Asked by At

I am trying to do spatial predictions with GAM and rasters. I have a raster file of depth data (Depth_R.asc), and presence and absence data of species from 248 locations (Depth.csv) . First I fitted these 248 data and then used raster:predict function to predict the occurrence probability of species over my whole study area depth data (Depth_R.asc). But when I want to do that I get following errors: Error in p[-naind, ] <- predv :   number of items to replace is not a multiple of replacement length In addition: Warning messages: 1: In predict.gam(model, blockvals, ...) :   not all required variables have been supplied in  newdata!

All data are available at:https://drive.google.com/drive/folders/15uRsWqgG0tcOlfuU9WSF-vTG6gJkuhLd?usp=sharing

My code is:

library(raster)
library(mgcv)
    
Data = read.csv("Depth.csv")
model <- gam(PA ~s(Depth), method="REML",family = binomial("logit"), data=Data)

X = raster("Depth_R.asc", level = 1) 
p <- raster::predict(X, model, type="response")

How to solve this problem?

1

There are 1 answers

0
Lime On

If you have a look here: Getting Warning: " 'newdata' had 1 row but variables found have 32 rows" on predict.lm

You find that there are mismatches with the names between the raster and the data.

For example:

class      : RasterLayer 
dimensions : 1276, 686, 875336  (nrow, ncol, ncell)
resolution : 0.005, 0.005  (x, y)
extent     : 88.9975, 92.4275, 17.9975, 24.3775  (xmin, xmax, ymin, ymax)
crs        : NA 
source     : E:/dissertation/dissertation/Depth_R.asc 
names      : Depth_R 

#AND
> names(Data)
[1] "PA"    "Depth"
  1. As you can see the names for X is Depth_R and for Data its Depth.

All you need to do is:

names(X) <- "Depth"

model <- gam(PA ~s(Depth), method="REML",family = binomial("logit"), data=Data)

p <- raster::predict(X, t, type="response")

> p
class      : RasterLayer 
dimensions : 1276, 686, 875336  (nrow, ncol, ncell)
resolution : 0.005, 0.005  (x, y)
extent     : 88.9975, 92.4275, 17.9975, 24.3775  (xmin, xmax, ymin, ymax)
crs        : NA 
source     : memory
names      : layer 
values     : 2.220446e-16, 0.9585746  (min, max)

enter image description here