R的“terra”库中的resample()函数在特定情况下无法正常工作

lokaqttq  于 2023-02-06  发布在  其他
关注(0)|答案(2)|浏览(230)

在下面的代码中,我尝试使用resample(x, y, method = "sum")将一个高分辨率的光栅重采样为一个低分辨率的光栅,但是重采样后的光栅在一些边缘显示为NA。

library(terra)
set.seed(42)

low_res <- rast(xmin = -1.05, xmax = 1.05, ymin = -0.05, ymax = 2.05, res = 0.5)

high_res <- rast(xmin = -1, xmax = 1, ymin = 0, ymax = 2, res = 0.01)
high_res[] <- runif(ncell(high_res))
plot(high_res, colNA = "darkblue")

resampled <- resample(high_res, low_res, method = "sum")
plot(resampled, colNA = "darkblue")
plot(as.polygons(low_res), add=TRUE, border='black', lwd=1)

高分辨率光栅:

重采样栅格(深蓝色像元为NA):

但是,如果对低分辨率栅格的范围进行四舍五入(即删除_.05),则一切看起来都很好:

library(terra)
set.seed(42)

##################################
# only changed extent here
low_res <- rast(xmin = -1, xmax = 1, ymin = -0, ymax = 2, res = 0.5) 
##################################

high_res <- rast(xmin = -1, xmax = 1, ymin = 0, ymax = 2, res = 0.01)
high_res[] <- runif(ncell(high_res))
plot(high_res, colNA = "darkblue")

resampled <- resample(high_res, low_res, method = "sum")
plot(resampled, colNA = "darkblue")
plot(as.polygons(low_res), add=TRUE, border='black', lwd=1)

重采样栅格:

9ceoxa92

9ceoxa921#

您所遇到的问题是由于GDAL中的一个错误fixed
我看不出GDAL 3.6有什么问题(在您的第一个示例中

library(terra)
gdal()
#[1] "3.6.0"

这里有一篇关于GDAL versions与R包的文章。
现在,您可以在Windows上通过从R-devel和RTools 43的源代码安装来获得GDAL版本3.6.2,在OSX上通过从当前版本的brew的源代码安装来获得GDAL版本3.6.2。

cngwdvgl

cngwdvgl2#

好的,我认为,如果low_res栅格中的像元不在high_res栅格的范围内,则其值将为NA(我希望不是这样)。因此,作为一种解决方案,我尝试使用extend()在high_res栅格周围添加像元(我认为,扩展high_res的保守大小应该是low_res光栅的分辨率大小)。下面的代码运行良好:

library(terra)

set.seed(42)
low_res <- rast(xmin = -1.05, xmax = 1.05, ymin = -0.05, ymax = 2.05, res = 0.5)

high_res <- rast(xmin = -1, xmax = 1, ymin = 0, ymax = 2, res = 0.01)
high_res[] <- runif(ncell(high_res))
plot(high_res, colNA = "darkblue")

#######################################
# add paddings around high_res raster
# with at least the resolution size of low_res raster
add_n_cells <- ceiling(res(low_res) / res(high_res))
high_res <- extend(high_res, add_n_cells)
plot(high_res, colNA = "darkblue")
#######################################

resampled <- resample(high_res, low_res, method = "sum")
plot(resampled, colNA = "darkblue")
plot(as.polygons(low_res), add=TRUE, border='black', lwd=1)

高分辨率光栅扩展:

最终重采样栅格:

相关问题