Sliding window function in R

后端 未结 2 1640
南方客
南方客 2020-12-18 11:51

Does somebody know whether there is a sliding window method in R for 2d matrices and not just vectors. I need to apply median function to an image stored in matrix

2条回答
  •  长情又很酷
    2020-12-18 12:35

    The function focal() in the excellent raster package is good for this. It takes several arguments beyond those shown in the example below, and can be used to specify a non-rectangular sliding window if that's needed.

    library(raster)
    
    ## Create some example data
    m <- matrix(1, ncol=10, nrow=10)
    diag(m) <- 2
    r <- as(m, "RasterLayer") # Coerce matrix to RasterLayer object
    
    ## Apply a function that returns a single value when passed values of cells
    ## in a 3-by-3 window surrounding each focal cell 
    rmean <- focal(r, w=matrix(1/9, ncol=3, nrow=3), fun=mean)
    rmedian <- focal(r, w=matrix(1/9, ncol=3, nrow=3), fun=median)
    
    ## Plot the results to confirm that this behaves as you'd expect
    par(mfcol=c(1,3))
    plot(r)
    plot(rmean)
    plot(rmedian)
    
    ## Coerce results back to a matrix, if you so desire
    mmean <- as(rmean, "matrix")
    

    enter image description here

提交回复
热议问题