library(raster)
#> Loading required package: sp
#> Warning: no function found corresponding to methods exports from 'raster' for:
#> 'area'
circ_matrix <- function(n){
if (!n %% 2){
stop("n must be an odd number.")
}
n.e <- n+1L
r <- n.e/2
m = matrix(1,n.e,n.e)
g = expand.grid(1:nrow(m), 1:nrow(m))
g$d2 = sqrt ((g[1]-r)^2 + (g[2]-r)^2)
g$inside = ifelse(g$d2 <= r, 1, NA)
m <- xtabs(inside ~ Var1 + Var2, data = g, addNA =FALSE)
m[m==0] <- NA
m[1:n, 1:n]
}
circ_matrix(11) # for example
#> Var2
#> Var1 1 2 3 4 5 6 7 8 9 10 11
#> 1 1 1 1 1 1 1 1
#> 2 1 1 1 1 1 1 1 1 1
#> 3 1 1 1 1 1 1 1 1 1 1 1
#> 4 1 1 1 1 1 1 1 1 1 1 1
#> 5 1 1 1 1 1 1 1 1 1 1 1
#> 6 1 1 1 1 1 1 1 1 1 1 1
#> 7 1 1 1 1 1 1 1 1 1 1 1
#> 8 1 1 1 1 1 1 1 1 1 1 1
#> 9 1 1 1 1 1 1 1 1 1 1 1
#> 10 1 1 1 1 1 1 1 1 1
#> 11 1 1 1 1 1 1 1
r <- raster(ncols=100, nrows=100, extent(0, 100, 0, 100))
uniq_classes <- 1:5 # cover class or whatever
values(r) <- sample(uniq_classes, ncell(r), replace = TRUE) # random raster
plot(r)
ras <- lapply(uniq_classes, function(x){
my_func <- function(y){
length(which(y==x)/length(y)*100)
}
focal(r, w=circ_matrix(11), fun=my_func)
}) |>
stack()
plot(ras)
Created on 2022-07-20 by the reprex package (v2.0.1)
I tried with {terra} too but I couldn't get the custom function working...