I use artificial grid cells (Polygons) for Sub-Saharan Africa to do a sub-national study. I have many variables assigned to each grid cell. Now, I need to include information (development aid programs) from the surrounding grid cells as control variables. By now, I try it with this code and with the raster package. (gid stands for the cell id)

  for(entries in nrow(dataset)){
      current_cell <- dataset[entries,]
      current_cell_id <- current_cell$gid
      prio_cell <- cellsSSA[cellsSSA$gid == current_cell_id]
      prio_cell_buffer <- buffer(prio_cell,50000)
      neighbor_prio_gids <- cellsSSA$gid[prio_cell_buffer,]
      neighbor_data <- subset(dataset, is.element(gid,neighbor_prio_gids))
      dataset$neighbor_aid[entries] <- min(neighbor_data$AID)

As I want to estimate the effect for many years, I got 85.000 grid cells and R runs now for 6 days. Any ideas to make this code more efficient or any other way to solve my problem? Is there a buffer function that is more efficient?

  • If your data is in a grid, perhaps you should be using rasters and not polygons. With rasters you can use a focal filter. It is not fast, but with only ~85000 cells, it should be a matter of hours, not days. – Mikkel Lydholm Rasmussen Jul 4 '18 at 8:32
  • Thank you very much for the advice. I know this question is a bit cheeky, but could you help me how to rewrite the code. I just want to include informations from the neighboring cells.Thank you very much in advance! – Amelio Tornincasa Jul 4 '18 at 16:17
  • The code snippet that you have is not really something that can be used for reproduction and testing. It requires an example dataset etc. – Mikkel Lydholm Rasmussen Jul 4 '18 at 17:07

Your Answer

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

Browse other questions tagged or ask your own question.