-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
getting-started.qmd
1171 lines (845 loc) · 32.8 KB
/
getting-started.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Getting Started with `R` for Data Analysis {#sec-gettingStarted}
The book uses `R` for statistical analyses (<http://www.r-project.org>).
R is a free software environment; you can download it at no charge here: <https://cran.r-project.org>.
## Learning `R` {#sec-learningR}
Here are a various resources for learning `R`:
- Intro to `R`: <https://www.statmethods.net>
- Video training courses in `R` skills: <https://www.pluralsight.com/search?q=R>
- Browse the `Cookbook for R` to find solutions to common tasks and problems: <http://www.cookbook-r.com>
- Browse the `R Graph Gallery` to find examples of various graphs: <https://r-graph-gallery.com>
- Free `Codeacademy` course on `R`: <https://www.codecademy.com/learn/learn-r>
- Free `Coursera` courses on `R`: <https://www.coursera.org/search?query=R>
- Watch these videos from `Coursera`: <https://blog.revolutionanalytics.com/2012/12/coursera-videos.html>
- `Posit`/`Rstudio` Webinars: <https://posit.co/resources/videos/>
- UCLA Stats Website: <https://stats.idre.ucla.edu/r/>
- Introduction to `R` course on `Datacamp`: <https://www.datacamp.com/courses/free-introduction-to-r>
- Teaching `R` in a Kinder, Gentler, More Effective Manner: <https://github.com/matloff/TidyverseSkeptic>
- Learn `R` interactively with `swirl`: <https://swirlstats.com>
- Use the `learnr` package: <https://rstudio.github.io/learnr/>
- Resources for learning `tidyverse`, which is a collection of `R` packages for data management: <https://www.tidyverse.org/learn/>
- You will sometimes find relevant articles on `R-bloggers`: <https://www.r-bloggers.com>
## Getting Help with `R` {#sec-gettingHelpR}
If you have `R` questions, you can ask them in a number of places:
- Forums:
- `Posit`: <https://forum.posit.co>
- `StackOverflow`: <https://stackoverflow.com/questions/tagged/r>
- `Reddit`: <https://www.reddit.com/r/rstats/>
- The `R` mailing list: <https://stat.ethz.ch/mailman/listinfo/r-help>
The following article provides additional resources and good guidance: <https://www.r-bloggers.com/where-to-get-help-with-your-r-question/>.
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.
- Provide a minimal, reproducible example.
Providing a minimal, reproducible example can be crucial for getting a helpful response.
By going to the trouble of creating a minimal, reproducible example and identifying the minimum conditions necessary to reproduce the issue, you will often figure out how to resolve it.
Here are guidelines on providing a minimal, reproducible example: <https://stackoverflow.com/help/minimal-reproducible-example> (archived at <https://perma.cc/6NUB-UTYF>).
Here are a good example and guidelines for providing a minimal, reproducible example in `R`: <https://stackoverflow.com/a/5963610> (archived at <https://perma.cc/PC9L-DQZG>).
My strong recommendation is to provide a `reprex` whenever possible: <https://reprex.tidyverse.org>.
## Initial Setup {#sec-initialSetup}
To get started, follow the following steps:
1. Install `R`: <https://cran.r-project.org>
1. Install `RStudio Desktop`: <https://posit.co/download/rstudio-desktop>
1. After installing `RStudio`, open `RStudio` and run the following code in the console to install several key `R` packages:
```{r}
#| eval: false
install.packages(
c("petersenlab","remotes","nflreadr","nflfastR","nfl4th","nflplotR",
"gsisdecoder","progressr","lubridate","tidyverse","psych"))
```
1. Some necessary packages, including the `ffanalytics` package, are hosted in GitHub and need to be installed using the following code (after installing the `remotes` package above):
```{r}
#| eval: false
remotes::install_github("FantasyFootballAnalytics/ffanalytics")
```
::: {#nte-gettingStarted .callout-note title="If you are in Dr. Petersen's class"}
If you are in Dr. Petersen's class, also perform the following steps:
1. Download and install `git`: <https://git-scm.com/downloads>
1. Set up a free account on [GitHub.com](https://github.com).
1. Download and install `GitHub Desktop`: <https://desktop.github.com>
1. Make sure you are logged into your GitHub account on [GitHub.com](https://github.com).
1. Go to the following GitHub repository: <https://github.com/isaactpetersen/QuartoBlogFantasyFootball> and complete the following steps:
1. Click "Use this Template" (in the top right of the screen) > "Create a new repository"
1. Make sure the checkbox is selected for the following option: "Include all branches"
1. Make sure your Owner account is selected
1. Specify the repository name to whatever you want, such as `FantasyFootballBlog`
1. Type a brief description, such as `Files for my fantasy football blog`
1. Keep the repository public (this is necessary for generating your blog)
1. Select "Create repository"
1. After creating the new repository, make sure you are on the page of of your new repository and complete the following steps:
1. Click "Settings" (in the top of the screen)
1. Click "Actions" (in the left sidebar) > "General"
1. 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"
1. Click "Pages" (in the left sidebar)
1. Make sure the following are selected:
- "Deploy from a branch" (under "Source")
- "gh-pages/(root)" (under "Branch")
- then click "Save"
1. 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"
:::
## Installing Packages {#sec-installingPackages}
You can install `R` packages using the following syntax:
```{r}
#| eval: false
install.packages("INSERT_PACKAGE_NAME_HERE")
```
For instance, you can use the following code to install the `tidyverse` package:
```{r}
#| eval: false
install.packages("tidyverse")
```
## Load Packages {#sec-loadPackages}
```{r}
library("tidyverse")
```
## Using Functions and Arguments {#sec-functionsArguments}
You can learn about a particular function and its arguments by entering a question mark before the name of the function:
```{r}
#| eval: false
?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:
```{r}
#| eval: false
?seq()
```
This is what the documentation shows for the `seq()` function in the `Usage` section:
```{r}
#| eval: false
seq(
from = 1,
to = 1,
by = ((to - from)/(length.out - 1)),
length.out = NULL,
along.with = NULL,
...)
```
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 @tbl-seqFunction:
| Argument | Default Value for Argument |
|:-------------|:---------------------------------|
| `from` | `1` |
| `to` | `1` |
| `by` | `((to - from)/(length.out - 1))` |
| `length.out` | `NULL` |
| `along.with` | `NULL` |
: Arguments and defaults for the `seq()` function. Arguments with a default of `NULL` are not used unless a value is provided by the user. {#tbl-seqFunction}
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:
```{r}
seq(1, 9)
```
Here is an example of providing values to the arguments by naming its arguments:
```{r}
seq(
from = 1,
to = 9,
by = 1)
```
If you provide values to arguments by naming the arguments, you can reorder the arguments and get the same answer:
```{r}
seq(
by = 1,
to = 9,
from = 1)
```
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:
```{r}
seq(
from = 1,
to = 9,
by = 2)
```
Or, alternatively, you could specify the length of the desired sequence (5 values):
```{r}
seq(
from = 1,
to = 9,
length.out = 5)
```
If you want to generate a series with decimal values, you could specify a long desired sequence of 81 values:
```{r}
seq(
from = 1,
to = 9,
length.out = 81)
```
This is equivalent to specifying a sequence from 1 to 9 by 0.1:
```{r}
seq(
from = 1,
to = 9,
by = 0.1)
```
Hopefully, that provides an example for how to learn about a particular function, its arguments, and how to use them.
## Create a Vector {#sec-createVector}
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.
```{r}
exampleVector <- c(40, 30, 24, 20, 18, 23, 27, 32, 26, 23, NA, 37)
```
We can then access the contents of the object by calling its name:
```{r}
exampleVector
```
## Create a Data Frame {#sec-createDF}
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:
```{r}
players <- data.frame(
ID = 1:12,
name = c(
"Ken Cussion",
"Ben Sacked",
"Chuck Downfield",
"Ron Ingback",
"Rhonda Ball",
"Hugo Long",
"Lionel Scrimmage",
"Drew Blood",
"Chase Emdown",
"Justin Time",
"Spike D'Ball",
"Isac Ulooz"),
position = c("QB","QB","QB","RB","RB","WR","WR","WR","WR","TE","TE","LB"),
age = c(40, 30, 24, 20, 18, 23, 27, 32, 26, 23, NA, 37)
)
fantasyPoints <- data.frame(
ID = c(2, 7, 13, 14),
fantasyPoints = c(250, 170, 65, 15)
)
fantasyPoints_weekly <- expand.grid(
ID = 1:12,
season = c(2022, 2023),
week = 1:17
)
set.seed(52242)
fantasyPoints_weekly$fantasyPoints <- sample(
0:35,
size = nrow(fantasyPoints_weekly),
replace = TRUE
)
```
## Create a List {#sec-createList}
A list can store multiple data frames in one object:
```{r}
exampleList <- list(players, fantasyPoints, fantasyPoints_weekly)
```
## Load a Data Frame {#sec-gettingStartedLoadData}
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):
```{r}
load(file = "./data/nfl_players.RData")
```
The following code loads a file from an *absolute path*:
```{r}
#| eval: false
nfl_players <- read.csv("C:/Users/myusername/nfl_players.RData")
```
Here is how you load a `.csv` file:
```{r}
#| eval: false
nfl_players <- read.csv("./data/nfl_players.csv") # relative path
nfl_players <- read.csv("C:/Users/myusername/nfl_players.csv") # absolute path
```
## Save a Data Frame {#sec-gettingStartedSaveData}
Here is how you save a `.RData` file using a *relative path*:
```{r}
#| eval: false
save(
nfl_players,
file = "./data/nfl_players.RData")
```
The following code saves a file to an *absolute path*:
```{r}
#| eval: false
save(
nfl_players,
file = "C:/Users/myusername/nfl_players.RData")
```
Here is how you save a `.csv` file:
```{r}
#| eval: false
write.csv(
nfl_players,
file = "./data/nfl_players.csv") # relative path
write.csv(
nfl_players,
file = "C:/Users/myusername/nfl_players.csv") # absolute path
```
## Variable Names {#sec-variableNames}
To see the names of variables in a data frame, use the following syntax:
```{r}
names(nfl_players)
names(players)
names(fantasyPoints)
```
## Logical Operators {#sec-logicalOperators}
### Is Equal To: `==` {#sec-logicalOperatorEqual}
```{r}
players$position == "RB"
```
### Is Not Equal To: `!=` {#sec-logicalOperatorNotEqual}
```{r}
players$position != "RB"
```
### Is Greater Than: `>` {#sec-logicalOperatorGreaterThan}
```{r}
players$age > 30
```
### Is Less Than: `<` {#sec-logicalOperatorLessThan}
```{r}
players$age < 30
```
### Is Greater Than or Equal To: `>=` {#sec-logicalOperatorGreaterThanEqual}
```{r}
players$age >= 30
```
### Is Less Than or Equal To: `<=` {#sec-logicalOperatorLessThanEqual}
```{r}
players$age <= 30
```
### Is In a Value of Another Vector: `%in%` {#sec-logicalOperatorInVector}
```{r}
players$position %in% c("RB","WR")
```
### Is Not In a Value of Another Vector: `!(%in%)` {#sec-logicalOperatorNotInVector}
```{r}
!(players$position %in% c("RB","WR"))
```
### Is Missing: `is.na()` {#sec-logicalOperatorMissing}
```{r}
is.na(players$age)
```
### Is Not Missing: `!is.na()` {#sec-logicalOperatorNotMissing}
```{r}
!is.na(players$age)
```
### And: `&`{#sec-logicalOperatorAnd}
```{r}
players$position == "WR" & players$age > 26
```
### Or: `|` {#sec-logicalOperatorOr}
```{r}
players$position == "WR" | players$age > 23
```
## Piping {#sec-piping}
In base `R`, if you want to perform multiple operations, it is common to either a) nest the operations, or b) save the object at each step.
Below is an example of nested operations:
```{r}
length(names(nfl_players))
```
Below is an example of saving the intermediate object at each step:
```{r}
variableNames <- names(nfl_players)
variableNames
lengthOfVariableNames <- length(variableNames)
lengthOfVariableNames
```
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.
#### Base `R` {#sec-pipingBaseR}
```{r}
nfl_players |>
names() |>
length()
```
#### Tidyverse {#sec-pipingTidyverse}
```{r}
nfl_players %>%
names() %>%
length()
```
## Subset {#sec-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:
```{r}
#| eval: false
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
### One Variable {#sec-subsetOneVariable}
To subset one variable, use the following syntax:
```{r}
players$name
```
or:
```{r}
players[,"name"]
```
### Particular Rows of One Variable {#sec-subsetParticularRowsOneVariable}
To subset one variable, use the following syntax:
```{r}
players$name[which(players$position == "RB")]
```
or:
```{r}
players[which(players$position == "RB"), "name"]
```
### Particular Columns (Variables) {#sec-subsetParticularColumns}
To subset particular columns/variables, use the following syntax:
#### Base `R` {#sec-subsetParticularColumnsBaseR}
```{r}
subsetVars <- c("name","age")
players[,c(2,4)]
players[,c("name","age")]
players[,subsetVars]
```
Or, to drop columns:
```{r}
dropVars <- c("name","age")
players[,-c(2,4)]
players[,!(names(players) %in% c("name","age"))]
players[,!(names(players) %in% dropVars)]
```
#### Tidyverse {#sec-subsetParticularColumnsTidyverse}
```{r}
players %>%
select(name, age)
players %>%
select(name:age)
players %>%
select(all_of(subsetVars))
```
Or, to drop columns:
```{r}
players %>%
select(-name, -age)
players %>%
select(-c(name:age))
players %>%
select(-all_of(dropVars))
```
### Particular Rows {#sec-subsetParticularRows}
To subset particular rows, use the following syntax:
#### Base `R` {#sec-subsetParticularRowsBaseR}
```{r}
subsetRows <- c(4,5)
players[c(4,5),]
players[subsetRows,]
players[which(players$position == "RB"),]
```
#### Tidyverse {#sec-subsetParticularRowsTidyverse}
```{r}
players %>%
filter(position == "WR")
players %>%
filter(position == "WR", age <= 26)
players %>%
filter(position == "WR" | age >= 26)
```
### Particular Rows and Columns {#sec-subsetParticularRowsAndColumns}
To subset particular rows and columns, use the following syntax:
#### Base `R` {#sec-subsetParticularRowsAndColumnsBaseR}
```{r}
players[c(4,5), c(2,4)]
players[subsetRows, subsetVars]
players[which(players$position == "RB"), subsetVars]
```
#### Tidyverse {#sec-subsetParticularRowsAndColumnsTidyverse}
```{r}
players %>%
filter(position == "RB") %>%
select(all_of(subsetVars))
```
## View Data {#sec-viewData}
### All Data {#sec-viewDataAll}
To view data, use the following syntax:
```{r}
#| eval: false
View(players)
```
### First 6 Rows/Elements {#sec-viewDataHead}
To view only the first six rows (if a data frame) or elements (if a vector), use the following syntax:
```{r}
head(nfl_players)
head(nfl_players$display_name)
```
## Data Characteristics {#sec-dataCharacteristics}
### Data Structure {#sec-dataCharacteristicsStructure}
```{r}
str(nfl_players)
```
### Data Dimensions {#sec-dataCharacteristicsDimensions}
Number of rows and columns:
```{r}
dim(nfl_players)
```
Number of rows:
```{r}
nrow(nfl_players)
```
Number of columns:
```{r}
ncol(nfl_players)
```
### Number of Elements {#sec-dataCharacteristicsLength}
```{r}
length(nfl_players$display_name)
```
### Number of Missing Elements {#sec-dataCharacteristicsMissingElements}
```{r}
length(nfl_players$college_name[which(is.na(nfl_players$college_name))])
```
### Number of Non-Missing Elements {#sec-dataCharacteristicsNonMissingElements}
```{r}
length(nfl_players$college_name[which(!is.na(nfl_players$college_name))])
length(na.omit(nfl_players$college_name))
```
## Create New Variables {#sec-createNewVars}
To create a new variable, use the following syntax:
```{r}
players$newVar <- NA
```
Here is an example of creating a new variable:
```{r}
players$newVar <- 1:nrow(players)
```
```{r}
#| include: false
players$newVar <- NULL
```
## Recode Variables {#sec-recodeVars}
Here is an example of recoding a variable:
```{r}
players$oldVar1 <- NA
players$oldVar1[which(players$position == "QB")] <- "quarterback"
players$oldVar1[which(players$position == "RB")] <- "running back"
players$oldVar1[which(players$position == "WR")] <- "wide receiver"
players$oldVar1[which(players$position == "TE")] <- "tight end"
players$oldVar2 <- NA
players$oldVar2[which(players$age < 30)] <- "young"
players$oldVar2[which(players$age >= 30)] <- "old"
```
Recode multiple variables:
```{r}
players %>%
mutate(across(c(
oldVar1:oldVar2),
~ case_match(
.,
c("quarterback","old","running back") ~ 0,
c("wide receiver","tight end","young") ~ 1)))
```
## Rename Variables {#renameVars}
```{r}
players <- players %>%
rename(
newVar1 = oldVar1,
newVar2 = oldVar2)
```
Using a vector of variable names:
```{r}
#| eval: false
varNamesFrom <- c("oldVar1","oldVar2")
varNamesTo <- c("newVar1","newVar2")
players <- players %>%
rename_with(~ varNamesTo, all_of(varNamesFrom))
```
## Convert the Types of Variables {#convertVarTypes}
One variable:
```{r}
players$factorVar <- factor(players$ID)
players$numericVar <- as.numeric(players$age)
players$integerVar <- as.integer(players$newVar1)
players$characterVar <- as.character(players$newVar2)
```
Multiple variables:
```{r}
players %>%
mutate(across(c(
ID,
age),
as.numeric))
players %>%
mutate(across(
age:newVar1,
as.character))
players %>%
mutate(across(where(is.factor), as.character))
```
## Merging/Joins {#sec-merging}
### Overview {#sec-mergingOverview}
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).
```{r}
mergeExample1A <- data.frame(
player = c("A","A","A","B","B"),
age = c(20,22,24,26,28)
)
mergeExample1B <- data.frame(
player = c("A","A","B","B"),
points = c(10,15,20,25)
)
mergeExample1 <- full_join(
mergeExample1A,
mergeExample1B,
by = "player")
mergeExample1
dim(mergeExample1)
```
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.
```{r}
mergeExample2A <- data.frame(
player = c("A","B","C","D","E"),
points = c(20,22,24,26,28)
)
mergeExample2B <- data.frame(
player = c("A","B","C","F"),
points = c(10,15,20,25)
)
mergeExample2 <- full_join(
mergeExample2A,
mergeExample2B,
by = "player")
mergeExample2
```
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.
```{r}
mergeExample3A <- data.frame(
player = c("A","B","C","D","E"),
weight = c(225,250,275,300,325)
)
mergeExample3B <- data.frame(
player = c("A","A","A","A","B","B"),
season = c(2023,2023,2024,2024,2024,2024),
week = c(1,2,1,2,3,4),
points = c(10,15,20,25,30,35)
)
mergeExample3 <- full_join(
mergeExample3A,
mergeExample3B,
by = "player")
mergeExample3
```
### Data Before Merging {#sec-mergingData}
Here are the data in the `players` object:
```{r}
players
dim(players)
```
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:
```{r}
fantasyPoints
dim(fantasyPoints)
```
### Types of Joins {#sec-mergeTypes}
#### Visual Overview of Join Types {#sec-mergeTypesVisual}
Below is a visual that 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`.
![Types of merges/joins](images/joinTypes.png)\
#### Full Outer Join {#sec-fullJoin}
A full outer join includes all rows in `x` **or** `y`.
It returns columns from `x` and `y`.
Here is how to merge two data frames using a full outer join (i.e., "full join"):
```{r}
fullJoinData <- full_join(
players,
fantasyPoints,
by = "ID")
fullJoinData
dim(fullJoinData)
```
#### Left Outer Join {#sec-leftJoin}
A left outer join includes all rows in `x`.
It returns columns from `x` and `y`.
Here is how to merge two data frames using a left outer join ("left join"):
```{r}
leftJoinData <- left_join(
players,
fantasyPoints,
by = "ID")
leftJoinData
dim(leftJoinData)
```
#### Right Outer Join {#sec-rightJoin}
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"):