按点坐标从栅格堆栈中提取数据时处理 NA

问题描述 投票:0回答:1

我正在处理不同物种存在的数据点。我用 R 创建随机的缺席和存在点。我堆叠了一堆不同的栅格,例如来自 BioClim 的高程、方向、地质数据和气候变量。当我使用存在/不存在点提取栅格信息时,我的问题就出现了,因为某些点落在某些栅格的无效单元格上,并且 NA 被归因。我想知道如何将此 NA 更改为最接近的可能有效值。

提前致谢。

我尝试使用 for 和 if 循环,但没有成功。我与 ChatGPT 进行了一些交谈,但它建议我使用 na.approx 和类似的方法插入数据,或者向包栅格中的提取函数添加参数,例如 methor="bilinear" 或一些无用的函数。

我目前的工作流程: 我加载栅格和 shapefile 函数“raster”和“readOGR”并定义我的扩展名。然后我检查所有栅格和点是否对齐,并使用“stack”功能堆叠所有栅格。我使用“spsample”生成缺席点,并将点文件创建为 SpatialPointsDataFrame。然后:

extracted_predictors_raw=data.frame(raster::extract(stack,points))%>%
 left_join(Legend_geo,by=c("Geology"="ORDRE"))%>%
 select(-Geologia,-extracted_predictors_raw$Legend_geo,-LEGEND)

spg_data=cbind(points@data,points@coords,extracted_predictors_raw)

coordinates(spg_data)=c("lon","lat")

NA_SPG=na.omit(spg_data@data)

mtry <- tuneRF(NA_SPG[,c(-Presence)],as.factor(NA_SPG$Presence), ntreeTry=500,
               stepFactor=1.5,improve=0.01, trace=TRUE, plot=TRUE)
best.m <- mtry[mtry[, 2] == min(mtry[, 2]), 1]

rf1 <- randomForest(as.factor(Presence) ~.,
                    data=NA_SPG, 
                    mtry=best.m[1],
                    na.action=na.omit,
                    replace = TRUE,
                    ntree=10000)

所以我想删除 NA,从最接近该点的有效单元格中获取值。当他们通过 kNN 处理它时,我读了一些论文,但我是在 R 上处理空间数据的新手。

r gis raster r-raster
1个回答
0
投票

这里有不同的解决方案:

  1. 将提取限制为栅格堆栈中的非 NA 值(在我看来这是最好的)
  2. 从数据库中删除出现 NA 的点
  3. 根据栅格分辨率和 NA 的出现,提取每个点周围缓冲区中的栅格值并取平均值(或中值,或您需要的任何值)。这并不能保证不存在 NA。

解决方案实际上取决于您的需求。如果您需要精确数量的存在/缺席点,则应调整 1) 和 2) 解决方案以达到您需要的点数。 只是第一个解决方案的简单示例

library(terra)
set.seed(4)
f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)
#create raster stack
rr <- c(r,r*2,r/2,log(r))
ncell <- ncol(r)*nrow(r)
#put some random NAs 
for (i in 1:nlyr(rr)) {
  rr[[i]][sample(1:ncell,ncell/2,replace=F)] <- NA
}
plot(rr)
#sample excluding NA values
pnt <- spatSample(rr,500,"random",as.points=T,na.rm=T)
summary(pnt)

如果你想要固定数量的点,你可以采样直到达到你想要的数量:

#calculate the maximum number of finite values in the stack
max_point <- sum(apply(is.finite(values(rr)),1,sum)==4)ù
#sample 50% of the total area
npoint <- max_point/2
pnt<- spatSample(rr,npoint,"random",as.df=T,na.rm=T,xy=T)

while (nrow(pnt)!=npoint) {
  x <- spatSample(rr,npoint,"random",as.df=T,na.rm=T,xy=T)
  pnt <- rbind(pnt,x)
  pnt <- dplyr::distinct(pnt)
  if (nrow(pnt)>npoint) {
    pnt <- pnt[1:npoint,]
    break
  }
}

附注由于

spatSample
具有参数
values=T
,因此您不需要在样本之后提取栅格值(即不需要
extract(raster,point,...)

© www.soinside.com 2019 - 2024. All rights reserved.