Error in predicting raster with Hmsc package in R

37 views Asked by At

Description:

I am trying to predict values in a raster using the Hmsc package in R. I have followed the example in the package's vignette for univariate analysis, but when I attempt to predict on a raster, I encounter the following error:

Error in sam$Beta : $ operator is invalid for atomic vectors

Reproducible exaple

I have been using the Hmsc package, and it has excellent features, however, as a user of usual SDM package, I cant figure out how to make predictions to rasters or more clearly SpatRaster, to make it very simple I have used the example in their first vignette.

So this would be fitting the model:

library(Hmsc)

set.seed(1)

n = 50
x = rnorm(n)

XData = data.frame(x = x)

alpha = 0
beta = 1

L = alpha + beta*x

y = 1*(L+ rnorm(n, sd = 1)>0)

Y=as.matrix(y)

nChains = 2

thin = 5
samples = 1000
transient = 500*thin
verbose = 500*thin


m = Hmsc(Y=Y, XData=XData, XFormula=~x, distr="probit")

m = sampleMcmc(m, thin = thin, samples = samples, transient = transient,
               nChains = nChains, nParallel = nChains)

mpost = convertToCodaObject(m)

Then I want to try to predict into a raster, so I make a fake SpatRast dataset:

library(terra)

x <- rast(nrows=100, ncols=100)

set.seed(2023)



values(x) <- rnorm(n = ncell(x))
names(x) <- "x"

You can see the spatraster here

enter image description here

Then I would like to predict the lone species prediction in this raster, so I have made several tries but here is my best try

Best try

If I try this:

Pred <- terra::predict(x, m, fun = Hmsc:::predict.Hmsc)

I get the following error:

Error in sam$Beta : $ operator is invalid for atomic vectors

Any idea on how I could get this prediction right?

0

There are 0 answers