1 year ago

#383952

test-img

Maxerature

How to Iterate through rasters and shapefiles faster?

I have 3 datasets, 2 rasters and 1 shapefile. I need to extract values from all 3 at the center of each grid cell for the raster with the more precise resolution. I then need to do some calculations on the results. What can I do to make this faster? Is there a faster method than manually polling each location via over() and extract()?

# Setup Sums
sumCasePol = 0
sumCasePop = 0
sumPopPol  = 0

#Get projections
caseCRS = CRS(proj4string(nations))
polCRS = crs(polData, proj=TRUE)
popCRS = crs(popData, proj=TRUE)

#Begin loop (poll south to north first, west to east second)
for(x in seq(-179.995,179.995, 0.01)) { # West-East resolution
  pb = txtProgressBar(min=-54.995, max=67.995, style=3, width=200, char="=") # Setup progress bar to know program hasn't stalled
  print(x) #Print x to know program overall progress
  for(y in seq(-54.995, 67.995, 0.01)) { # South-North resolution
    setTxtProgressBar(pb, y) 

    # Create projected coordinates
    caseCoord = SpatialPoints(cbind(x, y), proj4string=caseCRS)
    polCoord = vect(rbind(c(x, y)), type="points", crs=polCRS)
    popCoord = vect(rbind(c(x, y)), type="points", crs=popCRS)
    
    # Get value for caseVal
    caseVal = over(caseCoord, nations)$cases
    
    #Do calculations where values exist
    if(!is.na(caseVal)) {
      #Get rank
      caseRank = caseRanks[match(caseVal, caseValues)]
      
      #test polVal
      #Get value for polVal
      polVal = extract(polData, polCoord)$GWRPM25
      if(!is.na(polVal)) {
        polRank = polRanks[match(polVal, polValues)]
        dif = (caseRank-polRank)^2
        sumCasePol = sumCasePol + dif
      }
      
      #test popVal
      popVal = extract(popData, popCoord)$COUNT
      if(!is.na(popVal)) {
        popRank = popRanks[match(polVal, polValues)]
        dif = (caseRank-popRank)^2
        sumCasePop = sumCasePop + dif
      }
      
      #test polVal and popVal
      if(!is.na(polVal) && !is.na(popVal)) {
      polRank = polRanks[match(polVal, polValues)]
      popRank = popRanks[match(polVal, polValues)]
        dif = (popRank-polRank)^2
        sumPopPol = sumPopPol + dif
      }
    }
    
    #Not best practice to rewrite code, but this is a quick and easy method for testing these two 
    else {
      popVal = extract(popData, popCoord)$COUNT
      polVal = extract(polData, polCoord)$GWRPM25
     if(!is.na(polVal) && !is.na(popVal)) {
      polRank = polRanks[match(polVal, polValues)]
      popRank = popRanks[match(polVal, polValues)]
        dif = (popRank-polRank)^2
        sumPopPol = sumPopPol + dif
      }
    }
  }
}

r

time

raster

shapefile

0 Answers

Your Answer

Accepted video resources