R/get_top10_goalkeepers.R

#' Returns a data frame with top 10 goalkeeper statistics for a team or the whole league
#'
#'
#' @param season Season to be used, i.e. '2015' for the SHL season 2015/2016
#' @param team_id An ID for the team which the list should be based on, for example "DIF"
#' @param acces_token an access_token generated by get_shl_access_token()
#' @export
#' @examples
#' \dontrun{
#' get_top10_goalkeepers(season = "2018", team_id = "DIF")
#' }

get_top10_goalkeeper_stats <- function(season = season, team_id = NULL,
                                   access_token = get_shl_access_token()) {

  # Search SHL API for top goalkeepers
  res <- GET(url = stringr::str_glue('https://openapi.shl.se/seasons/{season}/statistics/goalkeepers'),
             query = list("teamIds[]" = team_id),
             add_headers(Authorization = paste("Bearer", access_token, sep = " "))) %>%
    content()

  if (!is.null(res$error)) {
    stop(str_glue('{res$error$message} ({res$error$status})'))
  }


  num_loops <- seq_len(length(res))

  top_10_players <- purrr::map_dfr(num_loops, function(this_row){
    this_player <- res[[this_row]]

    list(
      gp = this_player$gp,
      gpi = this_player$gpi,
      name = paste(this_player$info$first_name, this_player$info$last_name),
      birthdate = this_player$info$birthdate,
      height = this_player$info$height,
      weight = this_player$info$weight,
      rank = this_player$rank,
      nationality = this_player$info$nationality,
      number = this_player$info$number,
      player_id = this_player$info$player_id,
      #position = this_player$info$position,
      team = this_player$info$team_code,
      ga = this_player$ga,
      gaa = ifelse(length(this_player$gaa) == 0, NA, this_player$gaa),
      gs = this_player$gs,
      l = this_player$l,
      mip = this_player$mip,
      so = this_player$so,
      soga = this_player$soga,
      svs = this_player$svs,
      svsperc = ifelse(length(this_player$svsperc) == 0, NA, this_player$svsperc) * 0.01,
      t = this_player$t,
      valid_ranking = this_player$valid_ranking,
      w = this_player$w
    )
  }) %>%
    mutate(birthdate = as.Date(birthdate))

  return(top_10_players)
}
filipwastberg/shlr documentation built on May 17, 2019, 1:14 a.m.