简体   繁体   English

如何在 R 中为栅格进行最近邻插值?

[英]How to do nearest neighbour interpolation in R for a raster?

I have a raster image for which I would like to interpolate the values for NA only.我有一个光栅图像,我只想插入 NA 的值。 The missing NA's are usually in the border of the image.缺失的 NA 通常位于图像的边缘。 I am fairly new to R so I am not sure how exactly to do it.我对 R 相当陌生,所以我不确定该怎么做。 The accuracy of the values doesn't have to be higher and I would like to do just nearest neighbour interpolation.值的准确性不必更高,我只想做最近邻插值。 Any helps and suggestions or welcome.任何帮助和建议或欢迎。 I have added a simplified code to genetae a raster which has NA values on the border but ideally this NA value would be on all 4 sides of the raster.我添加了一个简化的代码来生成一个在边界上具有 NA 值的栅格,但理想情况下,这个 NA 值将在栅格的所有 4 个边上。 I found a post similar to filling NA gaps Fill in gaps (eg not single cells) of NA values in raster using a neighborhood analysis but it doesnt work for me.我发现了一个类似于填充 NA 间隙的帖子使用邻域分析填充栅格中 NA 值的间隙(例如,不是单个单元格),但它对我不起作用。

rast <- raster(nrow=10, ncol=10, crs='+proj=utm +zone=1 +datum=WGS84', xmn=0, xmx=1, ymn=0, ymx=1)
values(rast) <- 1:ncell(rast)
values(rast)[1:20] <- NA

"It does not work for me" is not sufficient. “它对我不起作用”是不够的。 Please show what you tried and explain why that does not work for you.请展示您尝试过的内容并解释为什么这对您不起作用。

I think you can use the focal function for that.我认为您可以为此使用焦点 function。 If you have NAs at the border and other places, I think the below is the simplest approach如果您在边境和其他地方有 NA,我认为以下是最简单的方法

I use a bit more complex example data.我使用了一些更复杂的示例数据。 The first two rows are NA, and there are also NAs in the middle前两行是NA,中间也有NA

library(raster)

r <- raster(nrow=10, ncol=10, crs='+proj=utm +zone=1 +datum=WGS84', xmn=0, xmx=1, ymn=0, ymx=1)
values(r) <- 1:ncell(r)
r[c(1:2, nrow(r)), ] <- NA
r[, 1] <- NA
r[3:5, 3:5] <- NA
plot(r)

w <- matrix(1, 3, 3)  #c(0,1,0,1,0,1,0,1,0), nrow=3)
x <- focal(r, w, mean, na.rm=TRUE, NAonly=TRUE, pad=TRUE)
plot(x)

Because the first row did not have any neighbors that are not NA we need to run the last line again因为第一行没有任何不是 NA 的邻居,我们需要再次运行最后一行

xx <- focal(x, w, mean, na.rm=TRUE, NAonly=TRUE, pad=TRUE)

plot(xx)
text(r, cex=.8)
text(mask(xx, r, inverse=TRUE), col="red", cex=.8)

在此处输入图像描述

Note that on a raster with square cells, there are four (rook case) nearest neighbors and 4 others that are nearby on the diagonal.请注意,在具有方形像元的栅格上,有四个(车箱)最近的邻居和其他 4 个在对角线上附近。 For the border row you could use this value for w to get the rook is not defined对于边框行,您可以使用w的此值来获取未定义的车

w <- matrix(c(0,1,0,1,0,1,0,1,0), nrow=3)

#     [,1] [,2] [,3]
#[1,]    0    1    0
#[2,]    1    0    1
#[3,]    0    1    0

But that would not work for the other cells (nor for the 4 corner cells).但这不适用于其他单元格(也不适用于 4 个角单元格)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM