使用邻域分析填写栅格中NA值的间隙(例如,不是单个像元) [英] Fill in gaps (e.g. not single cells) of NA values in raster using a neighborhood analysis

查看:76
本文介绍了使用邻域分析填写栅格中NA值的间隙(例如,不是单个像元)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的栅格中,NA值数量增加了

With the raster below, with an increased number of NA values

library(raster)
filename <- system.file("external/test.grd", package="raster")
r <- raster(filename)
r[r<300] <- NA
summary(getValues(r))

是否可以仅填充" NA细胞? 我一直在使用此有用的帖子,但如下所示,NA值保留在最终产品中.

is it possible to 'fill in' only the NA cells? I have been using this helpful post but as seen below, NA values remain in the final product.

fill.na <- function(x, i=5) {
  if( is.na(x)[i] ) {
    return( round(mean(x, na.rm=TRUE),0) )
  } else {
    return( round(x[i],0) )
  }
}  

r2 <- focal(r, w = matrix(1,3,3), fun = fill.na, 
            pad = TRUE, na.rm = FALSE )
summary(getValues(r2))

我怀疑问题在于具有NA值的连续区域,并且想知道是否还有其他选择来填补"缺失数据的空白.

I suspect the issue is the contiguous areas with NA values and am wondering if there are other options for 'filling in' gaps of missing data.

推荐答案

一种方法是扩大焦点窗口.您可以通过修改"fill.NA"函数以使用width参数并动态计算中心像素的位置来实现:

one way would be to enlarge your focus window. You can do so by modifying the "fill.NA" function to take a width argument and computing the position of the center pixel on the fly:

fill.na <- function(x) {
  center = 0.5 + (width*width/2) 
  if( is.na(x)[center] ) {
    return( round(mean(x, na.rm=TRUE),0) )
  } else {
    return( round(x[center],0) )
  }
}  

然后:

width = 9
r2 <- focal(r, w = matrix(1,width,width), fun = fill.na, 
            pad = TRUE, na.rm = FALSE)
summary(getValues(r2))

Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
300.0   339.0   408.0   488.7   574.5  1806.0    4661 

您可以看到NA的数量正在减少.

You can see that the number of NAs is going down.

但是,请注意,由于您的孔"共享栅格外部区域的相同NA值,因此这也会在外侧扩展栅格,使您得到虚假的值.参见例如:

However, be aware that since your "holes" share the same NA value of the area outside the raster, this will also expand your raster on the outer side, giving you bogus values. see for example:

width = 15
r2 <- focal(r, w = matrix(1,width,width), fun = fill.na, 
            pad = TRUE, na.rm = FALSE)
plot(rast)

因此,您必须找到一种方法来区分真实" NA值和数据集范围之外的值.

Therefore, you'd have to find a way to distinguish between "true" NA values, and values outside the extent of the dataset.

HTH.

这篇关于使用邻域分析填写栅格中NA值的间隙(例如,不是单个像元)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆