I have two raster layers with the same extent, CRS, and resolution, and a shapefile consisting of a number of polygons. I would like to calculate the Pearson correlation between the two rasters within each polygon, and write such values within a new attribute for all the polygons.

I work with QGIS and R.

  • You can convert the polygon to Raster then make the correlation using ERDAS Imagine (I can do this on ERDAS but on QGIS i can't because i'm a beginner of this software ) Jamal chaaouan GIS English – Jamal CHAAOUAN Aug 12 '18 at 9:24
  • Use raster::extract to retrieve the raster values for each polygon and then use apply or mapply to calculate the correlations. – Jeffrey Evans Dec 20 '18 at 4:14

I find this answer: Considering that all layers are identical in extent and resolution you could stack them all together and compute correlation among stacked objects simply with:

myfolder <- 'D:/myfolder' 
r_path <- file.path(myfolder, grep(".tif$", 
all.files = F), 
ignore.case = TRUE, value = TRUE)) 
mystack <- raster::stack(r_path) 
raster::layerStats(mystack, 'pearson')


  • But this does not consider the polygons, at all. It just produces a global figure. – Jackk Aug 13 '18 at 9:44

I am testing this solution. Please correct me if you spot mistakes.

summaryshapes<-list.files(pattern = "\\.shp$")

shapes<-lapply(summaryshapes, readogr)


crop_masked[i]<-for (i in 1:length(shapes)) {
  raster1_cropped <- crop(raster1, extent(shapes[[i]]))
  raster2_cropped<- crop(raster2, extent(shapes[[i]]))

b[X] <- stack(raster1_cropped[X],raster2_cropped[X])
corre[X] <- sampleRegular(b[X], 100000)
cor.test(corre[X][,1], corre[,2])

corr<-lapply(names(shapes), correlationfunction)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.