0

I'm trying to modify a CHELSA raster (download here [205MB download]) to fill the NA values in it, such as

require(terra)
require(raster)
file = "~/Downloads/CHELSA_bio14_2041-2070_gfdl-esm4_ssp126_V.2.1.tif"
r <- rast(file)

As suggested by Robert Hijmans, I used subst to remplace NA by 0 in my raster,

x <- subst(r, NA, 0)
plot(x)

After that, I try to save it using writeRaster but I get an error

writeRaster(x, fiename=file, overwrite=TRUE, filetype="GTiff", datatype='INT4S')
Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘writeRaster’ for signature ‘"SpatRaster", "missing"’

I don't understand why I have this error, I can't fix it.

1 Answer 1

0

Lets' read the error message and understand it:

writeRaster(x, fiename=file, overwrite=TRUE, filetype="GTiff", datatype='INT4S')
Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘writeRaster’ for signature ‘"SpatRaster", "missing"’

unable to find an inherited method for function ‘writeRaster’ for signature ‘"SpatRaster", "missing"’ is the thing to look at. You are calling writeRaster and its "signature" is "SpatRaster","missing". That means it thinks you called it like writeRaster(x), and in fact that generates the same error:

> writeRaster(r)
Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘writeRaster’ for signature ‘"SpatRaster", "missing"’

but you typed more.. You typed...

writeRaster(x, fiename=file, overwrite=TRUE, filetype="GTiff", datatype='INT4S')

And there's the problem: fiename not filename. R didn't match that argument to the definition of writeRaster, so it had a "missing" second argument, and writeRaster didn't know what to do with it.

1
  • I would add that a confounding factor is that you are also adding the raster package (which terra has replaced). Depending on the order that the packages are added to the environment, since both packages have the same function name, you could be masking terra::writeRaster with raster::writeRaster . Your error is likely do to the wrong function being called and rejecting the object class (function expecting RasterLayer and getting SpatRaster object). If for some reason you need the raster library, call functions from the package environment using package::function. Commented Jun 11 at 15:15

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.