r - 从栅格提取平均值期间返回的 NA
问题描述
我正在从具有多边形 shapefile 的栅格中提取平均值。栅格和矢量的 CRS 相同,但提取函数也返回 NA 值。
library(rgdal)
library(raster)
options(stringsAsFactors = FALSE)
Shapefile <- readOGR("Fishnet_geolocated.shp",layer="Fishnet_geolocated")
plot(Shapefile)
CHM_Napi<-raster("Napi_CRS.tif")
crs(Shapefile)
crs(CHM_Napi)
Napi_extract <- raster::extract(CHM_Napi, # the raster that you wish to extract values from
Shapefile, # a point, or polygon spatial object
fun = mean, # extract the MEAN value from each plot
sp = TRUE) # create spatial object
class(Napi_extract)
summary(Napi_extract$Napi_CRS)
运行此代码后,我得到一个结果-
> Shapefile <- readOGR("Fishnet_geolocated.shp",layer="Fishnet_geolocated")
OGR data source with driver: ESRI Shapefile
Source: ""
with 63 features
It has 5 fields
Integer64 fields read as strings: id
> plot(Shapefile)
> CHM_Napi<-raster("Napi_CRS.tif")
> crs(Shapefile)
CRS arguments:
+proj=utm +zone=36 +south +datum=WGS84 +units=m +no_defs +ellps=WGS84
+towgs84=0,0,0
> crs(CHM_Napi)
CRS arguments:
+proj=utm +zone=36 +south +datum=WGS84 +units=m +no_defs +ellps=WGS84
+towgs84=0,0,0
> class(Napi_extract)
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"
> summary(Napi_extract$Napi_CRS)
Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
NA NA NA NaN NA NA 63
提取函数中是否缺少某些内容,是否应该重新投影栅格和 shapefile。PS 在 QGIS 中,矢量和栅格层都重叠,但在 R 中没有。任何有用的提示都值得赞赏。
解决方案
栅格中可能有 NA 值。na.rm=TRUE
像这样使用
Napi_extract <- raster::extract(CHM_Napi, Shapefile, fun = mean, na.rm =TRUE, sp = TRUE)