Ted Kwartler - Sports Analytics in Practice with R
Здесь есть возможность читать онлайн «Ted Kwartler - Sports Analytics in Practice with R» — ознакомительный отрывок электронной книги совершенно бесплатно, а после прочтения отрывка купить полную версию. В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: unrecognised, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.
- Название:Sports Analytics in Practice with R
- Автор:
- Жанр:
- Год:неизвестен
- ISBN:нет данных
- Рейтинг книги:4 / 5. Голосов: 1
-
Избранное:Добавить в избранное
- Отзывы:
-
Ваша оценка:
- 80
- 1
- 2
- 3
- 4
- 5
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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
Table 1.1 Three simple control flows in R including the FOR loop, IF and IFELSE statement.
Name | Code | Description |
---|---|---|
FOR loops | for (i in 1:4){ print(i + 2) } |
The FOR loop has a dynamic variable ` i ` which will update a number of times. Here, the ` i ` value loop will repeat from 1, 2, 3, and 4. The code within the curly brackets executes with the updated ` i ` value. The first time through the loop ` i ` equals ` 1 ` and with ` + 2 ` the value 3 is printed to the console. The second time through ` i ` updates to ` 2 ` and is once again added with ` + 2 ` so that the value ` 4 ` is printed. This continues in the loop 4 times because of the ` 1:4 ` parameter |
IF statement | if(xVal == 1){ print('xVal is equal to one.') } |
The IF statement is a control operator. After the ` if ` code, a statement is created to check its validity. If the statement inside parentheses evaluates to TRUE, then the code within the curly brackets is executed. In this example, the statement checks whether a variable ` xVal ` is equal to ` 1 `. Since it does, the code in the curly brackets executes and a message is printed to the console state “xVal is equal to one.” If the statement does not evaluate to TRUE, the code inside the curly brackets is ignored. For example, if ` xVal == 2 `, then the code block is not run |
IF ELSE statement | if(xVal == 1){ print('xVal is equal to one.') } else { print('xVal is not equal to one.') } |
The IF-ELSE control flow adds another layer to the previous IF statement. Now a new set of curly brackets is added along with the ` else ` function. This statement will execute one of the two code chunks within the curly brackets based on the TRUE or FALSE result of the logical statement. Here, if ` xVal == 1 `, then the first message is printed, same as before. However, for any other value of ` xVal `, the second bit of code is run. For example, if ` xVal == 2 `, then the IF statement evaluates to FALSE and the second message “xVal is not equal to one” will be printed to the console. |
Another aspect of R programming is that it can utilize various data object types referred to as classes. Previously, the ` xVal
` object was a single numeric value, however can analyze and work the other common data types. First R can understand the difference between an integer, a whole number, and a numeric value. The distinction is that a numeric data type can be a number with a decimal. Although this difference can seem subtle in some computational work, this has an impact. If you’ve been following the simple code examples in this chapter, you should have ` xVal
`, ` newObj
` and an ` i
` variable from the previous FOR loop. Reviewing the “Environment” pane you will note the ` i
` variable has a ` 4L
` instead of just 4. This denotes that the variable is a whole number without a decimal. In contrast, the ` xVal
` object has a ` 1
` without the “L.” This means R is understanding this value to be a decimal or floating-point number. You can check the class difference using the ` class
` function applied to any object. Notice how the third `class` function call switches the returned value to “numeric” when a decimal is added. Often this distinction is not impactful but there are times as you will learn in this book that functions expect specific object types.
class(i) class(xVal) class(i +.01)
In addition to integers and numeric values, common R data types include “Boolean” values known in R as “logical” object types. Boolean data types are merely TRUE or FALSE. R can interpret these values as occurring or not occurring as shown in the IF statements. Additionally, for some operations, Boolean values can be interpreted as 1 and 0 for TRUE and FALSE, respectively. For example, in R ` TRUE + TRUE
` will return a value of ` 2
` while ` TRUE – FALSE
` will return ` 1
`, because R interprets the Boolean as 1 – 0. Let’s create a Boolean object called ` TFobj
` in the code below for use later.
TFobj <- TRUE
Another data type R often utilizes is a “factor.” A factor is a non-unique description of information. For example, a sports team may be assigned to a conference. Another team may also be assigned to that conference as well so it is frequently a repeating value within a data set. The factor has a level, meaning the conference name, and in effect the factor level alone represents specific “meta” information such as the other teams in the conference, and even perhaps some of the team’s schedule. This meta-information is inherited as a pattern within the larger data set, not explicitly defined within the object type. While this may be confusing, it will make sense eventually as the object types and classes move to multiple values instead of single values later in this chapter. The code below simply creates a single object, ` teamA
` with a factor defined as the Eastern conference. The function to declare value as a factor is simply ` as.factor
`.
teamA <- as.factor('Eastern_Conference')
In addition to factors, the last commonplace variable type includes “character.” Character objects represent natural language, for example, from social media or fan forums that need to be analyzed. The field of character and string analysis is referred to as Natural Language Processing (NLP). These methods and technology underpin the popular smart speakers and voice assistants among other everyday common technologies such as e-mail spam filters. This book devotes one chapter to gauging fan engagement on a popular forum. Thus, this type of data type will be covered extensively. However, one chapter merely covers the basics of NLP and much more can be accomplished with additional methods, code, and academic literature. Below is a fictitious social media post from a fan. Character values can be declared with ` as.character
` but, as written here, are not necessary.
fanTweet <- "I love baseball"
In review, Table 1.2reviews the common data types used in R and within the book. There are additional data types like ` NULL
` and ` NA
` but these are more straightforward, requiring less explanation. Once you have run all the code in the table, you can simply call ` class
` on each object to check that R is interpreting the object type as expected.
Table 1.2 Common R data types including integer, numeric, logical, factor, and character.
Name | Code | Description |
---|---|---|
“integer” | x <- 5L |
A whole number without a decimal point |
“numeric” | y <- 5.123 |
A floating point number |
“logical” | z <- TRUE z <- T #capital T or F is acceptable too |
A logical “Boolean” operator either TRUE or FALSE. R will interpret TRUE as 1 and FALSE as 0 for some operations |
“factor” | playerPosition <- as.factor(“forward”) |
A factor is a distinct class often representing non-unique information. The factor classes are referred to as “levels.” Here, a player position is defined as a factor with the level “forward” |
“character” | fanComment <- “I love the hot dogs at the stadium” |
Character values, known as strings, represent natural language. Unlike factors, they can be repeating or mutually exclusive. A growing subset of analytics work includes Natural Language Processing (NLP) |
Previously, the objects created such as ` xVal
` and ` i
` represented a single value. R’s coding environment relies on specific data types and corresponding classes that can be more complex than a single value. For instance, R can create and work with “vectors.” Vectors are merely columns of data that you may be familiar with if you’re coming to R from a spreadsheets program. To create a numeric vector, you employ the combine function which is ` c
`. In the following code, a vector of numbers is created called ` xVec
`. The ` xVec
` object utilizes some of the objects previously created along with additional values that are explicitly declared within the `c`, combine function. Each value within the vector is separated by a comma. Once ` xVec
` is created, calling in the console will return multiple values where the object such as ` xVal
` is now substituted to their numeric equivalents.
Интервал:
Закладка:
Похожие книги на «Sports Analytics in Practice with R»
Представляем Вашему вниманию похожие книги на «Sports Analytics in Practice with R» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Sports Analytics in Practice with R» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.