4

I'm not sure why the focal function I've been using in Raster does not work with Terra. This simplified example uses a custom function to apply the focal filter only to pixels with a value of 0 and it "grows" the pixels out to neighboring pixels (rooks case)....It works with raster, but I get the following message when attempting in Terra: Error: [Focal] test failed

library(raster)
tmpRas = raster(matrix(c(1:14,0,16:36,6,6))
plot(tmpRas)

enter image description here

grow0 = function(x){if (0%in%x){return(0)} else {return(x[5])}
w=matrix(c(NA,1,NA,1,1,1,NA,1,NA),3,3)
FocalRas = focal(tmpRas, w, fun = grow0, pad=TRUE, padValue = 1)
plot(FocalRas)

enter image description here

Any ideas on why this same method does not work with Terra, or is there an easier way to do what I'm trying to accomplish? Here is the same workflow using Terra:

library(terra)
tmpRast = rast(matrix(c(1:14,0,16:36),6,6)
FocalRast = focal(tmpRast, w, fun = grow0)

1 Answer 1

3

The example worked for me using:

library(terra)

tmpRast = rast(matrix(c(1:14,0,16:36),6,6)) # terra spatRaster object

grow0 = function(x){if (0%in%x){return(0)} else {return(x[5])}}
w=matrix(c(NA,1,NA,1,1,1,NA,1,NA),3,3)

FocalRast = terra::focal(tmpRast, w, fun = grow0) # terra::focal
plot(FocalRast)

It was only necessary to fix some minor bugs in the code. I also added terra::focal so that I used the function from the terra package. I'm not sure, but it's probably more efficient than raster::focal.

If it still doesn't work for you update your terra package to:

terra version 1.4.11
2
  • 2
    Thanks, that was helpful to know it was working for someone else! I was still getting the same error but now it works after updating my Terra package Commented Oct 18, 2022 at 15:46
  • 2
    @EricJeronimus: That's why it is a good idea to make use of {reprex} when creating minimal reproducing examples. After library(terra) you would have posted automatically terra 1.2.13 or some other outdated version - and everyone would have suggested to first update your package.. :)
    – dimfalk
    Commented Oct 18, 2022 at 19:44

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.