If raster value NA search and extract the nearest non-NA pixel

后端 未结 3 2123
既然无缘
既然无缘 2021-02-15 10:11

On extracting values of a raster to points I find that I have several NA\'s, and rather than use a buffer and fun arguments of extra

3条回答
  •  情歌与酒
    2021-02-15 10:35

    For a raster stack, use @koekenbakker's solution above, and turn it into a function. A raster stack's @layers slot is a list of rasters, so, lapply it across and go from there.

    #new layer
    r2 <- raster(ncol=10,nrow=10, xmn=0, xmx=10, ymn=0,ymx=10)
    r2[] <- 1:10
    r2[sample(1:ncell(r2), size = 25)] <- NA
    
    #make the stack
    r_stack <- stack(r, r2)
    
    #a function for sampling
    sample_raster_NA <- function(r, xy){
      apply(X = xy, MARGIN = 1, 
            FUN = function(xy) r@data@values[which.min(replace(distanceFromPoints(r, xy), is.na(r), NA))])
    
    }
    
    #lapply to get answers
    lapply(r_stack@layers, function(a_layer) sample_raster_NA(a_layer, xy))
    

    Or to be fancy (speed improvements?)

    purrr::map(r_stack@layers, sample_raster_NA, xy=xy)
    

    Which makes me wonder if the whole thing can be sped up even more using dplyr...

提交回复
热议问题