0
votes

I'm extracting mean values from a raster with polygon shapefile. The CRS of both raster and vector are same, but then also extract function returns NA values.

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)

After running this code I get a result-

> 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 

Is there something which I'm missing in the extract function, should I reproject the raster and shapefile. P.S. In QGIS both the vector and raster layer overlap, but not in R. Any useful tips are appreciated.

1

1 Answers

2
votes

There are probably NA values in the raster. Use na.rm=TRUE like this

Napi_extract <- raster::extract(CHM_Napi, Shapefile, fun = mean, na.rm =TRUE, sp = TRUE)