Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@h-a-graham
Last active July 20, 2022 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h-a-graham/e76b0cf6f7b81e8e2d7a2b90a2c7e9b2 to your computer and use it in GitHub Desktop.
Save h-a-graham/e76b0cf6f7b81e8e2d7a2b90a2c7e9b2 to your computer and use it in GitHub Desktop.
using a circular focal with terra
 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)

@h-a-graham
Copy link
Author

I tried with {terra} too but I couldn't get the custom function working...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment