[R-sig-Geo] Passing a custom function to raster::focal

Mirza Cengic mirzaceng at gmail.com
Tue Jan 10 15:59:26 CET 2017


Hi all,

I want to run the focal() function from the raster package with a custom
function. I want to calculate within a moving kernel (in the example I
provided 5x5), what is the percentage of cells with the value 1 (frequency
would work as well), and assign the value of the center cell of the moving
window. The error occurs when I run the focal function. I suppose the error
might come from using an inappropriate method on the object, but I am not
really sure how to solve it. Could you please give me some hints what am I
doing wrong.


Regards,
Mirza.

Example:

library(raster)
>
> my_rast <- raster(ncols=40, nrows=20, xmn=0)
> my_rast[] <- rnorm(ncell(my_rast))
>
> # Reclassify to binary raster
> my_mat <- c(cellStats(my_rast, min),cellStats(my_rast, max)/2,
>        cellStats(my_rast, max)/2, cellStats(my_rast, max), 0,1)
> my_rcl_mat <- matrix(my_mat, ncol=3, byrow=FALSE)
> my_rast_rcl <- reclassify(my_rast, my_rcl_mat)
>
> # Function to calculate percentage of cells with value of 1
> calc_pctg <- function(x)
> {
>   pct_val <- sum(values(x) == 1, na.rm = TRUE)/length(x)
>   return(pct_val)
> }
>
> # Run focal
> my_rast_fcl <- focal(my_rast_rcl,
>                      w = matrix(1/25,nrow=5,ncol=5),
>                      calc_pctg)





>

-- 
>
*Mirza Čengić*

*Junior Researcher | Department of Environmental Science*
Radboud University | Heyendaalseweg 135
6525 AJ Nijmegen | The Netherlands

+31 657020823 | +38761908392
Skype: mirzacengic
<https://www.linkedin.com/in/mirzacengic>

	[[alternative HTML version deleted]]



More information about the R-sig-Geo mailing list