njtierney / ukpolice

:uk: :police_car: R package to pull police data from the uk police data repository :police_car: :uk:
http://ukpolice.njtierney.com/
Other
36 stars 9 forks source link

Functionalise the first section of ukp_crime and ukp_stop_search #24

Open njtierney opened 5 years ago

njtierney commented 5 years ago

They are both very similar:

stop_search:


  # if date is used
  if (is.null(date) == FALSE) {

    result <- ukp_api(
      glue::glue("api/stops-street?lat={lat}&lng={lng}&date={date}")
    )

    # else if no date is specified
  } else if (is.null(date) == TRUE) {

    result <- ukp_api(
      glue::glue("api/stops-street?lat={lat}&lng={lng}")
    )

  }

  extract_result <- purrr::map_dfr(.x = result$content,
                                   .f = ukp_crime_unlist)

crime:


  # if date is used
  if (is.null(date) == FALSE) {

    result <- ukp_api(
      glue::glue("api/crimes-street/all-crime?lat={lat}&lng={lng}&date={date}")
              )

  # else if no date is specified
  } else if (is.null(date) == TRUE) {

    result <- ukp_api(
      glue::glue("api/crimes-street/all-crime?lat={lat}&lng={lng}")
    )

  }

  extract_result <- purrr::map_dfr(.x = result$content,
                                  .f = ukp_crime_unlist)
njtierney commented 5 years ago

Here it is again in ukp_crime_poly:

  # if date is used
  if (is.null(date) == FALSE) {

    result <- ukp_api(
      glue::glue("api/crimes-street/all-crime?poly={poly_string}&date={date}")
    )

    # else if no date is specified
  } else if (is.null(date) == TRUE) {

    # get the latest date
    # last_date <- ukpolice::ukp_last_update()

    result <- ukp_api(
      glue::glue("api/crimes-street/all-crime?poly={poly_string}")
    )
njtierney commented 5 years ago

Here are the main parts of all API calls

  1. Prepare the string to pass to ukp_api

    • Is there a date?
    • what is the longitude/lat?
    • is there a poly string?
    • what is the type of data? (crime? stop_search? poly?)
  2. Extract the content into a dataframe

  3. Give the columns sensible names

  4. make lat/long numeric

  5. reorder the columns

njtierney commented 5 years ago

Perhaps part 1 can be broken up into functions like so

# this inserts e.g. "stops-street" or "crimes-street/all-crime"
# depending upon input being "stop-street"
api_add_type <- function(type){
  switch()
  }

# add the type of call
api_type <- api_add_type(type)

# add lat long
if (!missing(lat) && !missing(long)){
api_type <- api_add_lat_long(api_type, lat, long)
}

# add poly string
if (!missing(poly)){
api_type <- api_add_poly(api_type, poly)
}
# add date
if (!is.null(date)) {
  api_type <- api_add_date(api_type, date)
}