1

I'm working on a project that involves counting how many crimes of a certain type happen within 150 meters or 500 meters of a list of addresses. While I've been able to do this successfully without a for-loop, it's a bit cumbersome because of the different crime definitions I need to use, so I'm trying to shorten the process a bit.

The dataframe with address points is about 2000 rows, and the crime points have around 80,000 rows -- definitely a good bit a data, but not so much that it keeps running for 20 mins plus.

Right now, here is the general structure of what I'm trying to do (edited):

function(input dataframe, crimedata1, crimedata2, distance, output){
 for (i in dataframe)
  1. create bounding box row i
  2. calculate number of intersections of boundingbox and file for two different files, based on the year the address is from
  3. return this count
}

countcrimes <- function(data, cdata1, cdata2, d, output){
  names <- c("ID", "year", "geometry")
  output <- data.frame(matrix(nrow = 2071, ncol = 3))
  colnames(output) <- names
  output$ID <- data$ID
  output$year <- data$year
  output$geometry <- data$geometry
  output <- st_as_sf(output, sf_column_name = "geometry", crs = 32616)
  for (i in 1:dim(output)[1]){ 
      if (output[i,]$year == 1){
      x <- st_intersection(crime1617_v, output)
      output[i,]$n <- st_intersection(cdata1, output[i,]) %>% count()
    } else if (output[i,]$year == 2){
      output[i,]$n <- st_intersection(cdata2, output[i,]) %>% count()
    }
  }
  return(output)
}

vc150m <- countcrimes(bbox150m, crime1516_v, crime1617_v, 150, vc150m)

Right now, I'm dealing with ridiculous runtime and unclear errors -- I'm thinking that the structure of what I'm trying to do isn't working, and I can't quite work out the issue or figure out a better way to structure this process.

1
  • You have a nearest neighbour problem, so look at using a package like RANN These work best with projected coordinate systems rather than the geographic one your use so use st_transform to switch to an appropriate CRS.
    – falcs
    Jan 20, 2020 at 10:56

0

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.