R/get_top10_player_stats.R

#' Returns a data frame with top 10 player statistics for a team or the whole league
#'
#'
#' @param season Season to be used, i.e. '2015' for the SHL season 2015/2016
#' @param sort Order of which the top list should be sorted, could be "goals" or "assists", defaults to "assists"
#' @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_teams()
#' }

get_top10_player_stats <- function(season = season, sort = "assists", team_id = NULL,
                                   access_token = get_shl_access_token()) {

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


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

  num_loops <- seq_len(length(res))

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

    list(
      games_played = this_player$gp,
      name = paste(this_player$info$first_name, this_player$info$last_name),
      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,
      toi = this_player$toi,
      toi_gp = this_player$toi_gp,
      assists = this_player$a,
      bk_s = this_player$bk_s,
      goals = this_player$g,
      gwg = this_player$gwg,
      hits = this_player$hits,
      minus = this_player$minus,
      plus = this_player$plus,
      pim = this_player$pim,
      ppg = this_player$ppg,
      sog = this_player$sog,
      tp = this_player$tp
    )
  })

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