The landscapemetrics::window_lsm
is very slow. You would be better served just using a focal function in raster or terra. Here is an example in terra, you can read in your raster using terra::rast
.
Add package and create an example 4 class raster.
library(terra)
r <- rast(nrow=1000, ncol=1000)
r[] <- sample(1:4, ncell(r), replace=TRUE)
Write a function that returns percent of class(s). We set the default to 2,3 as to illustrate that there may be more than one class of interest (eg., 2 forest classes). You can simply change the default value(s) to suit your data.
pclass <- function(x, y=c(2,3)) {
return( length(which(x %in% y)) / length(x) )
}
Now, we pass our pclass
function to the focal function thus, returning class percent within a 9x9 window.
( pf <- terra::focal(r, w=matrix(1, 9, 9), pclass) )
par(mfrow=c(2,1))
plot(r)
plot(pf)
If your raster is projected and you want a circular focal window you can use the focalMat function to create an appropriate matrix (in this example 90m radius). The one catch is that the function returns weights, which can be dealt with by replacing non-zero values with 1 (as shown). This matrix would then be passed to the w argument in terra::focal
.
f <- terra::focalMat(r, 90, "circle")
f[f > 0] <- 1