首页 > 解决方案 > 使用 R 中的提取函数处理 NA 值

问题描述

我正在尝试使用 CRU 数据库计算 11x11km 的网格单元的年平均温度(除非单元是沿海的,尺寸更小)。矢量和栅格的 CRS 相同。然而,1363 个细胞中有 332 个在提取后显示 NA 值。我想在使用数据集进行进一步分析之前填写 NA 值。知道如何处理这些缺失值吗?我在这个论坛(和其他论坛)上查看了几种可能的解决方案。不幸的是,它们似乎都不适用于我的情况。以下是我的工作流程的详细信息:

# load the temperature dataset 
temp <- brick("/CRU/cru_ts4.02.1901.2017.tmp.dat.nc", varname="tmp")
# set CRS for temp
utm = "+proj=utm +zone=49 +datum=WGS84 +towgs84=0,0,0"
tempro = projectRaster(temp, crs = utm, method = "bilinear")
# load the grid cells (in polygons) & set its CRS
fish <- st_read("/CRU/fish11.shp")
fishpro <- st_transform(fish, "+proj=utm +zone=49 +datum=WGS84 +towgs84=0,0,0")
# extract the temperature dataset 
tempgrid  <- extract(tempro, fishpro, fun='mean',  na.rm=TRUE, df=TRUE, weights = TRUE, small = TRUE, 
method='bilinear') 
write.csv(tempgrid, file="temp.csv") 

而地图是: 温度

标签: rgis

解决方案


我认为您的问题没有简单的答案。显然多边形不在陆地上;但我们无法确定,因为我们没有您的数据。也可能是选择的 UTM 区域不合适。

我可以说你的做法是错误的。如果您需要转换数据;您应该转换矢量数据,而不是栅格数据(即使这不会对 NA 问题产生太大影响,如果有的话)。

library(raster)
temp <- brick("/CRU/cru_ts4.02.1901.2017.tmp.dat.nc", varname="tmp")

fish <- st_read("/CRU/fish11.shp")
fishpro <- st_transform(fish, "+proj=longlat +datum=WGS84")

tempgrid  <- extract(temp, fishpro, fun='mean', na.rm=TRUE, df=TRUE, small = TRUE)
 

您还可以制作地图以查看正在发生的事情(并且可能将其作为图像包含在您的问题中。

 x <- crop(temp[[1]], extent(fishpro)+1)
 plot(x)
 lines(fishpro)

推荐阅读