**Adventures in Analytics and Visualization**, and kindly contributed to R-bloggers)

__can be found here.__

A visit to espn.com’s page at http://espn.go.com/mens-college-basketball/teams shows a listing of universities in different conferences. The image below presents one such example.

A click on the “Stats” link for a school will take you to a page like this.

The page provides two tables – one of game statistics – total games played and the per game statistics for the season for all players from that team and the second, cumulative numbers for the entire season. Tables in this format are useful, but they do not provide information on relationships between variables, between teams, or between conferences. So, the objective of this post is to visualize few of these relationships. In order to do this, we do the following.

**Steps**

1. Find a way to extract data from the website. Remember, each page for a college provides information on only one season, but information on 12 seasons is available. This is done using a function developed to scrape the site.

2. Clean and prepare the data.

3. Prepare preliminary graphs, and lastly,

4. Make the graph generation process interactive for people to focus on their favorite teams or variables.

**Scope of this post**

1. We focus only on the first of the two tables of statistics provided by espn.com (see the previous image) — total games played and per game statistics. Please note that these are player level data.

2. This post does not look at individual players, by name, in different teams — so it does not identify best players on any variable — but it uses player level data to study teams and conferences.

3. We look at only 20 teams, 10 each in the West Coast Conference and Big 12 —- but with some extra time, interest, and patience (TIP), it can be used for the remaining 331 Division 1 teams in 30 different basketball conferences.

4. Not all questions pertaining to variables studied are answered and not all graphical formats explored. For example, we do not have data on the win/loss record or of the competition teams faced.

**The fun begins…**

Step 1: Extracting Data

The image previously presented of a typical statistics page from espn has certain distinct elements.

1. Each page has two tables, the first about game statistics and the second about the season (cumulative numbers for the season), they have the same headers.

2. The URL for a page had three different parts.

(a) Part 1 has the team id, Part 2 the year, and Part 3 was the team name.

(b) The second part, year, represents a season — so when Part 2 is 2012, the page described the 2011-12 season. This is something to remember to make the necessary change in the data.

3. The basic idea is to create a function, which does the following. (i) Take in Part 1 and Part 3, among any other variables we deem appropriate as inputs;(ii) loop through pages representing different seasons for a team; (iii) from each page extract two tables and update two master data frames with data from these two tables — two because we have game stats and season stats (the latter is not used for analysis in this post — but the data is available for anyone wishing to look at them). This function should then be used to extract data for 20 universities.

First the libraries required for all of this code

Note that we have created columns for Year, Team, City, and Conference. — variables beyond the columns provided by the two tables and will either have to be calculated or manually determined. For each of the 20 colleges of interest from the 2 conferences, we can prepare something like the following.

The city information was obtained from Wikipedia for those I didn’t know and the other information was available on the espn page for that university. Once we have prepared the parameters required to send to our function (getData), we then call on it. Remember that the function should return two tables. This we collect in a list named gameandseasonstats and extract the updated master tables – Gamestatistics and Seasonstatistics tables from the list.

Now the function.

What this does is the following.

(a) Receive parameters we send to the function – getData

(b) For every year’s page, from 2002-2013, it assembles the complete URL of the page by adding URLpart1, the year, and URLpart3 together.

(c) Gets the two tables and stores them in two temporary tables — gamestat and seasonstat

(d) Adds new columns for year, team, city, and conference.

(e) Add these rows to the respective master tables – Gamestatistics and Seasonstatistics and return them in a list, which we retrieve outside the function and reuse them for the next school.

Now, we have collected data on 2 tables for 20 schools from 2 different conferences from 240 different pages from espn.com. On to the next stage.

Step 2 Clean and Prepare the Data

The dataframes have three types of rows which need to be removed. These are instances where the value of “Players” is either “Players”, “Total”, or “NA” (remember, we initialized empty dataframes). This is from the way tables were read by our function. That’s easy.

Converting few variables to factors and few to numbers was accomplished by these two lines.

Then, columns were renamed to explain each variable completely, so PPG became Points.Per.Game. This could’ve done this at the very beginning, but I didn’t have the foresight.

And the last thing left was converting years back to seasons — so 2002 became “2001-2002″, accomplished using this for years between 2002 and 2013.

Remember, these changes are required for the second table as well — Seasonstatistics, which we don’t use for the post. However, both these cleaned dataframes are available for anyone to play with. They are with the code at the github link provided previously.

Step 3: Prepare preliminary graphs

Which 20 schools did we collect data on?

Let’s plot these cities on a map.

First, get the US map from osm, get the list of cities from our data, get their latitudes and longitudes, and add this information to our data.

And, the plot.

1. BYU is in Utah, which isn’t a coastal state, unlike the other schools from the WCC.

2. WVU doesn’t exactly fit the region of the other Big 12 schools.

3. BYU and WVU recently joined these conferences.

Just a thought: On what bases are conferences named? Big 12 has 10 teams, but Big Ten has 12? Clearly, there appears to be a branding issue. PAC-10 did change to PAC-12 after the recent addition of two new teams. Hmm.

Let’s plot histograms of some variable, say Points.Per.Game, for all teams.

We could also compare the distributions of two different schools on one variable — let’s take a look at Gonzaga Bulldogs and Kansas Jayhawks on say, Points.Per.Game.

We might also be interested in seeing how the mean points per game of team players change over years for different teams.

Alternately, we might be interested in how the mean points per game of team players changed for two teams, across different seasons.

We could also look at relationships between two variables (Points per game and Assists.Per.Game) in teams across different years and add in a LOESS curve.

We could also compare the relationship of two variables – points per game and assists per game, for two or more schools.

Step 4: Interactively generate graphs – for any combination of variable and teams

Of course, previously shown graphs could be generated for comparing both conferences and we could also have other variables of interest that we might want to compare different schools or conferences on. It would be unwieldy to present graphs of all possibilities here. Introducing interactivity by letting you play around with variables and schools will help. For this, we rely on the shiny server platform from RStudio. Our shiny server application uses three preloaded data files – Gamestatisticscleaned.rda, and files for team-wise and conference-wise means (labeled meansteams.rda and meansconferences.rda, respectively) of all variables for all years and presents 9 different graphs. The code to generate these additional data files is given below.

**Please click on the screenshot below to access the application.**

**Concluding Remarks**

1. The objective of this post was to visualize few relationships between game statistics presented for teams by espn.com for two NCAA basketball conferences – West Coast and Big 12.

2. Data were scraped from 240 different pages on espn.com

3. Data on win/loss history or the competition teams faced was not available on the page and hence, not used.

4. Only one of two tables — one concerning game statistics – was used for the analyses and the data from the second table, season statistics —cumulative numbers for the entire season — is available for download from the previously provided link.

5. R code was formatted for the blog purpose using the Highlight 3.14 software.

6. I would appreciate any comments/suggestions you might have on the application or on the code. Thanks.

————————–

**leave a comment**for the author, please follow the link and comment on his blog:

**Adventures in Analytics and Visualization**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...