All examples By author By category About

timelyportfolio

NBA Game with R eventdropR htmlwidget


Building off the eventdropR github commit example, let's now use some NBA basketball data to create an EventDrop interactive timeline. Note, the time is actual time and not game time. Each made shot is considered the same regardless of 1, 2, or 3 points.

Code

# example using NBA game data
# http://stats.nba.com/game/#!/0021600991/playbyplay/

library(jsonlite)
library(eventdropR)
library(pipeR)
library(dplyr)

plays <- "http://stats.nba.com/stats/playbyplayv2?EndPeriod=10&EndRange=55800&GameID=0021600991&RangeType=2&Season=2016-17&SeasonType=Regular+Season&StartPeriod=1&StartRange=0" %>>%
  readLines() %>>%
  paste0(collapse = "\n") %>>%
  fromJSON() %>>%
  {.$resultSets$rowSet[[1]]} %>>%
  {
    tibble(
      date = .[,6],
      score = .[,11],
      team = .[,18]
    )
  } 

plays %>>%
  # change date to proper format
  mutate(
    date = sprintf(
      "2017-03-14T0%s:%s",
      Map(function(x) as.numeric(x[1])-7,strsplit(plays$date,":")),
      Map(function(x) substr(x[2],1,2),strsplit(plays$date,":"))
    )
  ) %>>%
  # get only score changes
  filter(Negate(is.na)(score)) %>>%
  filter(Negate(is.na)(team)) %>>%
  eventdrop(
    name = "team"
  )