I want your feedback to make the book better for you and other readers. If you find typos, errors, or places where the text may be improved, please let me know.
The best ways to provide feedback are by GitHub or hypothes.is annotations.
Alternatively, you can leave an annotation using hypothes.is.
To add an annotation, select some text and then click the
symbol on the pop-up menu.
To see the annotations of others, click the
symbol in the upper right-hand corner of the page.
When posting a question on forums or mailing lists, keep a few things in mind:
Read the posting guidelines before posting!
Be respectful of other people and their time. R is free software. People are offering their free time to help. They are under no obligation to help you. If you are disrespectful or act like they owe you anything, you will rub people the wrong way and will be less likely to get help.
After installing RStudio, open RStudio and run the following code in the console to install the R packages used in this book (note: this will take a while):
Some necessary packages, including the ffanalytics package(Andersen et al., 2025), are hosted in GitHub (and are not hosted on the Comprehensive R Archive Network [CRAN]) and thus need to be installed using the following code (after installing the remotes package (Csárdi et al., 2024) above)1:
Click “Use this Template” (in the top right of the screen) > “Create a new repository”
Make sure the checkbox is selected for the following option: “Include all branches”
Make sure your Owner account is selected
Specify the repository name to whatever you want, such as FantasyFootballBlog
Type a brief description, such as Files for my fantasy football blog
Keep the repository public (this is necessary for generating your blog)
Select “Create repository”
After creating the new repository, make sure you are on the page of of your new repository and complete the following steps:
Click “Settings” (in the top of the screen)
Click “Actions” (in the left sidebar) > “General”
Make sure the following are selected:
“Read and write permissions” (under “Workflow permissions”)
“Allow GitHub Actions to create and approve pull requests”
then click “Save”
Click “Pages” (in the left sidebar)
Make sure the following are selected:
“Deploy from a branch” (under “Source”)
“gh-pages/(root)” (under “Branch”)
then click “Save”
Clone the repository to your local computer by clicking “Code” > “Open with GitHub Desktop”, select the folder where you want the repository to be saved on your local computer, and click “Clone”
3.4 Installing Packages
You can install R packages using the following syntax:
Code
install.packages("INSERT_PACKAGE_NAME_HERE")
For instance, you can use the following code to install the tidyverse package (Wickham, 2023):
Code
install.packages("tidyverse")
3.5 Load Packages
Code
library("tidyverse")
3.6 Using Functions and Arguments
You can learn about a particular function and its arguments by entering a question mark before the name of the function:
Code
?NAME_OF_FUNCTION()
Below, we provide examples for how to learn about and use functions and arguments, by using the seq() function as an example. The seq() function creates a sequence of numbers. To learn about the seq() function, which creates a sequence of numbers, you can execute the following command:
Code
?seq()
This is what the documentation shows for the seq() function in the Usage section:
Based on this information, we know that the seq() function takes the following arguments:
from
to
by
length.out
along.with
...
The arguments have default values that are used if the user does not specify values for the arguments. The default values are provided in the Usage section and are in Table 3.1:
Table 3.1: Arguments and defaults for the seq() function. Arguments with a default of NULL are not used unless a value is provided by the user.
Argument
Default Value for Argument
from
1
to
1
by
((to - from)/(length.out - 1))
length.out
NULL
along.with
NULL
What each argument represents (i.e., the meaning of from, to, by, etc.) is provided in the Arguments section of the documentation. You can specify a function and its arguments either by providing values for each argument in the order indicated by the function, or by naming its arguments.
Here is an example of providing values to the arguments in the order indicated by the function, to create a sequence of numbers from 1 to 9:
Code
seq(1, 9)
[1] 1 2 3 4 5 6 7 8 9
Here is an example of providing values to the arguments by naming its arguments:
Code
seq(from =1,to =9,by =1)
[1] 1 2 3 4 5 6 7 8 9
If you provide values to arguments by naming the arguments, you can reorder the arguments and get the same answer:
Code
seq(by =1,to =9,from =1)
[1] 1 2 3 4 5 6 7 8 9
There are various combinations of arguments that one could use to obtain the same result. For instance, here is code to generate a sequence from 1 to 9 by 2:
Code
seq(from =1,to =9,by =2)
[1] 1 3 5 7 9
Or, alternatively, you could specify the length of the desired sequence (5 values):
Code
seq(from =1,to =9,length.out =5)
[1] 1 3 5 7 9
If you want to generate a series with decimal values, you could specify a long desired sequence of 81 values:
Hopefully, that provides an example for how to learn about a particular function, its arguments, and how to use them.
3.7 Create a Vector
A vector is a series of elements that can be numeric or character. It has one dimension (length). To create a vector, use the c() to combine elements into a vector. And, we use the assignment operator (<-) to assign the vector to an object named exampleVector, so we can access it later.
We can then access the contents of the object by calling its name:
Code
exampleVector
[1] 40 30 24 20 18 23 27 32 26 23 NA 37
3.8 Create a Data Frame
A data frame has two dimensions: rows and columns. Here is an example of creating a data frame, while using the assignment operator (<-) to assign the data frame to an object so we can access it later:
Here is how you load a .RData file using a relative path (i.e., a path relative to the working directory, where the working directory is represented by a period):
Code
load(file ="./data/nfl_players.RData")
To determine where you working directory is, you can type:
Code for performing nested operations can be challenging to read. Saving the intermediate object can be a waste of time to do if you are not interested in the intermediate object, and can take up unnecessary memory and computational resources. An alternative approach is to use piping. Piping allows taking the result from one computation and sending it to the next computation, thus allowing a chain of computations without saving the intermediate object at each step.
In base R, you can perform piping with the |> expression. In tidyverse you can perform piping with the %>% expression.
3.14.0.1 Base R
Code
nfl_players |>names() |>length()
[1] 32
3.14.0.2 Tidyverse
Code
nfl_players %>%names() %>%length()
[1] 32
3.15 Subset
To subset a data frame, use brackets to specify the subset of rows and columns to keep, where the value/vector before the comma specifies the rows to keep, and the value/vector after the comma specifies the columns to keep:
Code
dataframe[rowsToKeep, columnsToKeep]
You can subset by using any of the following:
numeric indices of the rows/columns to keep (or drop)
names of the rows/columns to keep (or drop)
values of TRUE and FALSE corresponding to which rows/columns to keep
Merging (also called joining) merges two data objects using a shared set of variables called “keys.” The keys are the variable(s) that are used to align the rows from the two objects. The data for the given key(s) in the first object get paired with (i.e., get placed in the same row as) the data for that same key in the second object. In general, each row should have a value on each of the keys; there should be no missingness in the keys. To merge two objects, the key(s) that will be used to match the records must be present in both objects. The keys are used to merge the variables in object 1 (x) with the variables in object 2 (y). Different merge types select different rows to merge.
For some data objects, you might want to combine information for the same player from multiple data objects. If each data object is in player form (i.e., player_id uniquely identifies each row), you might merge by the player’s identification number (e.g., player_id). In this case, the key uniquely identifies each row.
However, some data objects have multiple keys. For instance, in long form data objects, each player may have multiple rows corresponding to multiple seasons. In this case, the keys may be player_id and season—that is, the data are in player-season form. If object 1 and object 2 are both in player-season form, we would use player_id and season as the keys to merge the two objects. In this case, the keys uniquely identify each row; that is, they account for the levels of nesting.
However, if the data objects are of different form, we would select the keys as the variable(s) that represent the lowest common denominator of variables used to join the data objects that are present in both objects. For instance, assume that object 1 is in player-season form. For object 2, each player has multiple rows corresponding to seasons and games/weeks—in this case, object 2 is in player-season-week form. Object 1 does not have the week variable, so it cannot be used to join the objects. Thus, we would use player_id and season as the keys to merge the two objects, because both variables are present in both objects.
It is important not to have rows with duplicate values on the keys. For instance, if there is more than one row with the same player_id in each object (or multiple rows in object 2 with the same combination of player_id, season, and week), then each row with that player_id in object 1 gets paired with each row with that player_id in object 2. The many possible combinations can lead to the resulting object greatly expanding in terms of the number of rows. Thus, you want the keys to uniquely identify each row. In the example below, player is present in each object, so we can merge by player; however, each object has multiple rows with the same player. For example, mergeExample1A has three rows for player A; mergeExample1B has two rows for player A. Thus, when we merge them, the resulting object has many more rows than each respective object (even though neither object has players that the other object does not).
Note: if the two objects include variables with the same name (apart from the keys), R will not know how you want each to appear in the merged object. So, it will add a suffix (e.g., .x, .y) to each common variable to indicate which object (i.e., object x or object y) the variable came from, where object x is the first object—i.e., the object to which object y (the second object) is merged. In general, apart from the keys, you should not include variables with the same name in two objects to be merged. To prevent this, either remove or rename the shared variable in one of the objects, or include the shared variable as a key. However, as described above, you should include it as a key only if you want to use its values to align the rows from each object. Below is an example of merging two objects with the same variable name (i.e., points) that is not used as a key.
When two objects are merged that have different formats, the resulting data object inherits the format of the data object that has more levels of nesting. For instance, consider that you want to merge two objects, object A and object B. Object A is in player form and object B is in player-season-week form. When you merge them, the resulting data object will be in player-season-week form.
The data are structured in ID form. That is, every row in the dataset is uniquely identified by the variable, ID.
Here are the data in the fantasyPoints object:
Code
fantasyPoints
Code
dim(fantasyPoints)
[1] 4 2
3.22.3 Types of Joins
3.22.3.1 Visual Overview of Join Types
Figure 3.1 depicts various types of merges/joins. Object x is the circle labeled as x. Object y is the circle labeled as y. The area of overlap in the Venn diagram indicates the rows on the keys that are shared between the two objects (e.g., the same player_id, season, and week). The non-overlapping area indicates the rows on the keys that are unique to each object. The shaded blue area indicates which rows (on the keys) are kept in the merged object from each of the two objects, when using each of the merge types. For instance, a left outer join keeps the shared rows and the rows that are unique to object x, but it drops the rows that are unique to object y.
Figure 3.1: Types of Merges/Joins.
3.22.3.2 Full Outer Join
A full outer join includes all rows in xory. It returns columns from x and y. Here is how to merge two data frames using a full outer join (i.e., “full join”):
A right outer join includes all rows in y. It returns columns from x and y. Here is how to merge two data frames using a right outer join (“right join”):
An inner join includes all rows that are in bothxandy. An inner join will return one row of x for each matching row of y, and can duplicate values of records on either side (left or right) if x and y have more than one matching record. It returns columns from x and y. Here is how to merge two data frames using an inner join:
A semi join is a filter. A left semi join returns all rows from xwith a match in y. That is, it filters out records from x that are not in y. Unlike an inner join, a left semi join will never duplicate rows of x, and it includes columns from only x (not from y). Here is how to merge two data frames using a left semi join:
An anti join is a filter. A left anti join returns all rows from xwithout a match in y. That is, it filters out records from x that are in y. It returns columns from only x (not from y). Here is how to merge two data frames using a left anti join:
Depending on the analysis, it may be important to restructure the data to be in long or wide form. When the data are in wide form, each player has only one row. When the data are in long form, each player has multiple rows—e.g., a row for each game. The data structure is called wide or long form because a dataset in wide form has more columns and fewer rows (i.e., it appears wider and shorter), whereas a dataset in long form has more rows and fewer columns (i.e., it appears narrower and taller).
Here are the original data in long form. The data are structured in “player-season-week form”. That is, every row in the dataset is uniquely identified by the combination of variables, ID, season, and week—these are the keys. This is an example of long form, because each player has multiple rows.
Below, we widen the data by two variables (season and week), using tidyverse, so that the data are now in “player form” (where each row is uniquely identified by the ID variable):
Conversely, we can also restructure data from wide to long. Here are the data in long form, after they have been transformed from wide form using tidyverse:
If you want to perform the same computation multiple times, it can be faster to do it in a loop compared to writing out the same computation many times. For instance, here is a loop that runs from 1 to 12 (the number of players in the players object), incrementing by 1 after each iteration. The loop prints each element of a vector (i.e., the player’s name) and the loop index (i) that indicates where the loop is in terms of its iterations:
Code
for(i in1:length(players$ID)){print(paste("The loop is at index:", i, sep =" "))print(paste("My favorite player is:", players$name[i], sep =" "))}
[1] "The loop is at index: 1"
[1] "My favorite player is: Ken Cussion"
[1] "The loop is at index: 2"
[1] "My favorite player is: Ben Sacked"
[1] "The loop is at index: 3"
[1] "My favorite player is: Chuck Downfield"
[1] "The loop is at index: 4"
[1] "My favorite player is: Ron Ingback"
[1] "The loop is at index: 5"
[1] "My favorite player is: Rhonda Ball"
[1] "The loop is at index: 6"
[1] "My favorite player is: Hugo Long"
[1] "The loop is at index: 7"
[1] "My favorite player is: Lionel Scrimmage"
[1] "The loop is at index: 8"
[1] "My favorite player is: Drew Blood"
[1] "The loop is at index: 9"
[1] "My favorite player is: Chase Emdown"
[1] "The loop is at index: 10"
[1] "My favorite player is: Justin Time"
[1] "The loop is at index: 11"
[1] "My favorite player is: Spike D'Ball"
[1] "The loop is at index: 12"
[1] "My favorite player is: Isac Ulooz"
3.26 Session Info
At the end of each chapter in which R code is used, I provide the session information, which describes the system and operating system the code was run on and the versions of each package. That way, if you get different results from me, you can see which session settings differ, to help with reproducibility. If you run the (all of) the exact same code as is provided in the text, in the exact same order, with the exact same setup (platform, operating system, package versions, etc.) and the exact same data, you should get the exact same answer as is in the text. That is the idea of reproducibility—getting the exact same result with the exact same inputs. Reproducibility is crucial for studies to achieve greater confidence in their findings and to ensure better replicability of findings across studies.
Corston, R., & Colman, A. M. (2000). A crash course in SPSS for Windows. Wiley-Blackwell.
Csárdi, G., Hester, J., Wickham, H., Chang, W., Morgan, M., & Tenenbaum, D. (2024). remotes: R package installation from remote repositories, including GitHub. https://doi.org/10.32614/CRAN.package.remotes
Wickham, H., Averick, M., Bryan, J., Chang, W., McGowan, L. D., François, R., Grolemund, G., Hayes, A., Henry, L., Hester, J., Kuhn, M., Pedersen, T. L., Miller, E., Bache, S. M., Müller, K., Ooms, J., Robinson, D., Seidel, D. P., Spinu, V., … Yutani, H. (2019). Welcome to the tidyverse. Journal of Open Source Software, 4(43), 1686. https://doi.org/10.21105/joss.01686
Although the petersenlab package (Petersen, 2025) is hosted on CRAN, installing from GitHub will ensure you have the latest version.↩︎
Feedback
Please consider providing feedback about this textbook, so that I can make it as helpful as possible. You can provide feedback at the following link:
https://forms.gle/LsnVKwqmS1VuxWD18
Email Notification
The online version of this book will remain open access. If you want to know when the print version of the book is for sale, enter your email below so I can let you know.