I have a large multipolygon (5x5km grids) file (1.23 million polygons) that I would like to exact raster data to each polygon. Specifically I want to calculate the fractal dimensions (a user defined function), Morans I (from the raster
package), and the mean NDVI value of all the pixels that fall into each polygon.
The raster covers the extent of Australia. Each band has an associated date (919 total bands in the raster). Importantly, all polygons need only one specific band.
However, this loop takes such a long time (roughly 2 seconds per polygon). The crop command is what makes the loop run slowly. What is the best way to speed this loop up?
Below is the basic for loop
#adding column for final values to be returned
#spdf3_buffed is a sf object
spdf3_buffed$FractID <- 0
spdf3_buffed$meanNDVI$Moran <- 0
spdf3_buffed$meanNDVI <- 0
for (i in 1:nrow(spdf3_buffed)){
print(i)
spSubset <- spdf3_buffed[i,]
BandNumber <-spSubset$BandNumber
r <- raster(MODIS_raster_location,band=BandNumber)
cropped_raster <- crop(r, st_bbox(spSubset))
b <- as.numeric(fractalD(cropped_raster))
c <- as.numeric(Moran(cropped_raster))
layermeans <- cellStats(cropped_raster, stat='mean', na.rm=TRUE)
u <- mean(layermeans)
spdf3_buffed$FractID[[i]] <- b
spdf3_buffed$Moran[[i]] <- c
spdf3_buffed$meanNDVI[[i]] <- u
}
write.csv(spdf3_buffed,file="test.csv")