Last active
August 29, 2016 12:58
-
-
Save batpigandme/feb0328f77e3d7a0bc8b to your computer and use it in GitHub Desktop.
Gets all of the game logs for each player for each game in the NBA from the Stattleship API.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## install and load the stattleshipR package | |
devtools::install_github("stattleship/stattleship-r") | |
library(stattleshipR) | |
## get your API token stattleship.com | |
## set your API token | |
set_token('YOUR_ACCESS_TOKEN') | |
## set params according to | |
## developers.stattleship.com | |
sport <- "basketball" | |
league <- "nba" | |
ep <- "game_logs" | |
## leave q_body empty to get for all players | |
## set season_id | |
## for specific player or team use slug | |
q_body <- list(season_id="nba-2015-2016") | |
## get the game logs | |
games <- ss_get_result(sport=sport, league=league, ep=ep, query=q_body, version=1, verbose=TRUE, walk=TRUE) | |
## bind the data together | |
gl <- lapply(games, function(x) x$game_logs) | |
all_games <- do.call('rbind', gl) | |
all_games <- rbindlist(gl) | |
## clean-up data, set zero-out na | |
## for active player vars | |
i <- which(all_games$game_played == TRUE) | |
all_games <- all_games[i,] | |
all_games$field_goals_made[which(is.na(all_games$field_goals_made))] <- 0 | |
all_games$assists[which(is.na(all_games$assists))] <- 0 | |
all_games$rebounds_offensive[which(is.na(all_games$rebounds_offensive))] <- 0 | |
all_games$field_goals_attempted[which(is.na(all_games$field_goals_attempted))] <- 0 | |
all_games$turnovers[which(is.na(all_games$turnovers))] <- 0 | |
all_games$points[which(is.na(all_games$points))] <- 0 | |
## calculate offensive efficiency | |
all_games$oe <- (all_games$field_goals_made + all_games$assists) / (all_games$field_goals_attempted - all_games$rebounds_offensive + all_games$assists + all_games$turnovers) | |
## remove ineligible records | |
all_games <- all_games[-which(all_games$oe == Inf),] | |
## add player details | |
players <- lapply(games, function(x) x$players) | |
all_players <- do.call('rbind', players) | |
the_players <- all_players[match(all_games$player_id, all_players$id),] | |
all_games$player_name <- the_players[match(all_games$player_id, the_players$id),]$name | |
all_games$position <- the_players[match(all_games$player_id, the_players$id),]$position_abbreviation | |
## optional group by position | |
pos_grouped <- group_by(all_games, position) | |
OE_pos <- summarise(pos_grouped, meanOE = mean(oe, na.rm=TRUE)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment