Ted Kwartler - Sports Analytics in Practice with R

Здесь есть возможность читать онлайн «Ted Kwartler - Sports Analytics in Practice with R» — ознакомительный отрывок электронной книги совершенно бесплатно, а после прочтения отрывка купить полную версию. В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: unrecognised, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Sports Analytics in Practice with R: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Sports Analytics in Practice with R»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Sports Analytics in Practice with R
A practical guide for those looking to employ the latest and leading analytical software in sport Sports Analytics in Practice with R
Sports Analytics in Practice with R
Sports Analytics in Practice with R

Sports Analytics in Practice with R — читать онлайн ознакомительный отрывок

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Sports Analytics in Practice with R», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

# 1st element, 2nd row, 1st column xList[[1]][2,1]

Just to make things a bit more complex, if the list element is a data frame with named vectors, the second part of the code can employ the `$` along with the name. This will return the first list element, a data frame, and only the named column called “logical2.”

# 1st element, named column with $ xList[[1]]$logical2

Lastly, since the column of this list element is being accessed, it too can be indexed. Once again, the single column does not have a row and column pairing, it only has a position. Thus, no comma is needed and only the third position is returned in this example.

# 1st element, names column with $, third position xList[[1]]$logical2[3]

If all this seems wildly complex, do not fret. Throughout the book extensive explanation is given for both functions, inputs, and indexing. Further, with enough practice, this becomes commonplace and more readily understood.

So far, this basic explanation of R functionality has relied on base-R functions and libraries that are part of the standard installation. As mentioned previously, R can be specialized to a particular task by loading libraries. In order to obtain libraries, the ` install.packages` function must be run with a package name to download the specialized functions. This is done only once per library so that the library code is installed locally to your R installation. After the download occurs you can merely call the ` library` function with the name in order to enable the specialized functionality using the local installation. The code below installs a popular graphics library called “grammar of graphics” known as ` ggplot2` using the ` install.packages` function. After it is downloaded, the next line merely loads it as part of your R environment. This allows your R session to call functions within a “namespace” that includes base-R and now ` ggplot2` functions. It serves the purpose of specializing R for improved visualizations.

install.packages('ggplot2') library(ggplot2)

Throughout this book, multiple libraries are loaded. Novice R programmers can run into errors and frustrations regarding package installations. When executing scripts in this book that begin with ` library(…)`, an error of “there is no package called …” means you first need to use ` install.packages` to download the functionality to your library. Additionally errors may occur during the ` install.packages` step. This can be due to multiple reasons but most often stems from the fact that a package to be downloaded requires another package first. As a result, carefully read the console messages during the install phase to identify any other package prerequisites. If the ` install.packages` function executes correctly, then it is not necessary to repeat that function for each script. Thus, the code in this book only calls `library` for each specific library enabling corresponding functionality needed for the task at hand. This assumes all libraries have been previously and successfully installed.

To specialize R, first install a package with `install.packages` with the corresponding name. If installed without issue, simply call `library` any time your R session needs specialized functionality corresponding to the specific library. You will only need to use `install.packages` once but `library` will need to be called each time you start R and require the specialized functions of a particularly library.

In at least one instance in the book, a custom function is needed to make the code more concise. A custom function is like any other function loaded from a library. It is defined for an operation and requires an input and returns a value or object. The code below creates a simple custom function as an example. The function is declared as ` plus3` with the ` function` statement. Next, the input parameter is declared as ` x`. This means the function will be called ` plus3` and requires an input temporarily called ` x`. What happens to ` x` occurs within the curly brackets. In this case, a simple operation ` x + 3` overwrites the internal value of `x` and the new value is returned. The function will be an object in the environment and can accept any numeric or integer value. Here, the function is created and then applied to a value of 2. The output is assigned an object itself in ` exampleThree`.

plus3 <- function(x){ x <- x + 3 return(x) } exampleThree <- plus3(2) exampleThree

Of course, functions can be more complex. As an example, the following function is made to be more dynamic by adding a new parameter, called ` value`. Now both are required for the function to operate. The `x` value is now divided by the ` value` input parameter that is passed into the function. Additionally, before the result is returned from the function, the ` round` function is applied further adjusting the preceding division. In the end, for example, the custom function ` divideVal` will accept a number 5, divide it by 2, and then round the result so that it returns the value 2.

divideVal <- function(x, value){ x <- x / value x <- round(x) return(x) } exampleValue <- divideVal(5,2) exampleValue

Applying R Basics to Real Data

Let’s reward your laborious work though foundational R coding with something of actual interest utilizing sports data. Like many scripts in this book, let’s begin by loading packages. For each of these, you need to first run ` install.packages` and assuming that executes without error, the following library calls will specialize R for the task at hand. As an example, script using real sports data, our only goal is to obtain the data, manipulate it, and finally plot it.

To begin call ` library(RCurl)` which is a general network interface client. Functions within this library allow R to make a network connection to download the data. One could have data locally in a file, connect to an API, database, or even web scrape the data. However, in upcoming code, the data are download directly from an online repository. Next, ` library(ggplot2)` loads the grammar of graphics namespace with excellent visualization capabilities. The ` library(ggthemes)` call is a convenience library accompanying ` ggplot2` for quick, predefined aesthetics. Lastly, the ` library(tidyr)` functions are used for tidying data, which is a style of data organization that is efficient if not intuitive. Here, the basic raw will be rearranged before plotting.

library(RCurl) library(ggplot2) library(ggthemes) library(tidyr)

Next, before establishing a connection between R and the data repository, a character object is created called ` c1Data`. The character string is the web URL to the raw comma-separated value, CSV, file. If you open this web address in a typical browser, you will see the raw text-based statistics for regular season Dallas NBA team in the 2019–2020 season. However, the following code does not open a browser and instead downloads this simple file before loading it as an R object.

c1Data <- ‘https://raw.githubusercontent.com/kwartler/Practical_Sports_Analytics/main/C1_Data/2019-2020%20Dallas%20Player%20Stats.csv’

Now to execute a network connection employ the ` getURL` function which lies within the `RCurl` package. This function simply accepts the string URL address previously defined. Be sure to have the address exactly correct to avoid any errors. nbaFile <- getURL(c1Data)

Finally, the base-R function ` read.csv` is used with the downloaded data. The ` read.csv` function is widely used because CSV files are ubiquitous. Further, the function can accept a local file path leading to a hard disk rather than the file downloaded here but the path must be exactly correct. Spaces, capitalization, and misspellings will result in cryptic and frustrating file not found errors. Assuming the web address was correct, and the ` getURL` function executed without error, then the result of this code is a new object called ` nbaData`. It is automatically read in as a ` data.frame` object.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Sports Analytics in Practice with R»

Представляем Вашему вниманию похожие книги на «Sports Analytics in Practice with R» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Sports Analytics in Practice with R»

Обсуждение, отзывы о книге «Sports Analytics in Practice with R» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x