-
Notifications
You must be signed in to change notification settings - Fork 68
/
01-R.Rmd
869 lines (606 loc) · 34.5 KB
/
01-R.Rmd
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
# Introduction to `R` {#R-intro}
## Getting Started
`R` is both a programming language and software environment for statistical computing, which is *free* and *open-source*. To get started, you will need to install two pieces of software:
1. [`R`, the actual programming language.](https://www.r-project.org)
- Chose your operating system, and select the most recent version.
1. [RStudio, an excellent IDE for working with `R`.](http://www.rstudio.com/)
- Note, you must have `R` installed to use RStudio. RStudio is simply an interface used to interact with `R`.
The popularity of `R` is on the rise, and everyday it becomes a better tool for statistical analysis. It even generated this book!
The following few chapters will serve as a whirlwind introduction to `R`. They are by no means meant to be a complete reference for the `R` language, but simply an introduction to the basics that we will need along the way. Several of the more important topics will be re-stressed as they are actually needed for analyses.
This introductory `R` chapter may feel like an overwhelming amount of information. You are not expected to pick up everything the first time through. You should try all of the code from this chapter, then return to it a number of times as you return to the concepts when performing analyses. We only present the most basic aspects of `R`. If you want to know more, there are countless online tutorials, and you could start with the official [CRAN sample session](https://cran.r-project.org/doc/manuals/r-release/R-intro.html#A-sample-session) or have a look at the resources at [Rstudio](https://www.rstudio.com/online-learning/#DataScience) or on this [github repo](https://github.com/qinwf/awesome-R).
## Starting R and RStudio
A key difference for you to understand is the one between `R`, the actual programming language, and `RStudio`, a popular interface to `R` which allows you to work efficiently and with greater ease with `R`.
The best way to appreciate the value of `RStudio` is to start using `R` *without* `RStudio`. To do this, double-click on the R GUI that you should have downloaded on your computer following the steps above (on windows or Mac), or start R in your terminal (on Linux or Mac) by just typing `R` in a terminal, see figure \@ref(fig:console). You've just opened the R **console** which allows you to start typing code right after the `>` sign, called *prompt*. Try typing `2 + 2` or `print("Your Name")` and hit the return key. And *voilà*, your first R commands!
```{r console, fig.cap="R GUI symbol and R in a MacOS Terminal",fig.align='center',out.width="50%",echo=FALSE}
knitr::include_graphics(c("images/RLogo.png","images/console.png") )
```
Typing one command after the other into the console is not very convenient as our analysis becomes more involved. Ideally, we would like to collect all command statements in a file and run them one after the other, automatically. We can do this by writing so-called **script files** or just **scripts**, i.e. simple text files with extension `.R` or `.r` which can be *inserted* (or *sourced*) into an `R` session. RStudio makes this process very easy.
Open `RStudio` by clicking on the `RStudio` application on your computer, and notice how different the whole environment is from the basic `R` console – in fact, that *very same* `R` console is running in your bottom left panel. The upper-left panel is a space for you to write scripts – that is to say many lines of codes which you can run when you choose to. To run a single line of code, simply highlight it and hit `Command` + `Return`.
```{block, type='note'}
We highly recommend that you use `RStudio` for everything related to this course (in particular, to launch our apps and tutorials).
```
RStudio has a large number of useful keyboard shortcuts. A list of these can be found using a keyboard shortcut -- the keyboard shortcut to rule them all:
- On Windows: `Alt` + `Shift` + `K`
- On Mac: `Option` + `Shift` + `K`
The `RStudio` team has developed [a number of "cheatsheets"](https://www.rstudio.com/resources/cheatsheets/) for working with both `R` and `RStudio`. [This particular cheatseet for Base `R`](http://www.rstudio.com/wp-content/uploads/2016/05/base-r.pdf) will summarize many of the concepts in this document. ^[When programming, it is often a good practice to follow a style guide. (Where do spaces go? Tabs or spaces? Underscores or CamelCase when naming variables?) No style guide is "correct" but it helps to be aware of what others do. The more import thing is to be consistent within your own code. Here are two guides: [Hadley Wickham Style Guide](http://adv-r.had.co.nz/Style.html), and the [Google Style Guide](https://google.github.io/styleguide/Rguide.xml). For this course, our main deviation from these two guides is the use of `=` in place of `<-`. For all practical purposes, you should think `=` whenever you see `<-`.]
### First Glossary
* `R`: a statistical programming language
* `RStudio`: an integrated development environment (IDE) to work with `R`
* *command*: user input (text or numbers) that `R` *understands*.
* *script*: a list of commands collected in a text file, each separated by a new line, to be run one after the other.
## Basic Calculations
To get started, we'll use `R` like a simple calculator. Run the following code either directly from your RStudio console, or in RStudio by writting them in a script and running them using `Command` + `Return`.
#### Addition, Subtraction, Multiplication and Division {-}
| Math | `R` code | Result |
|:-------------:|:-------:|:---------:|
| $3 + 2$ | `3 + 2` | `r 3 + 2` |
| $3 - 2$ | `3 - 2` | `r 3 - 2` |
| $3 \cdot2$ | `3 * 2` | `r 3 * 2` |
| $3 / 2$ | `3 / 2` | `r 3 / 2` |
#### Exponents {-}
| Math | `R` code | Result |
|:-------------:|:-------:|:---------:|
| $3^2$ | `3 ^ 2` | `r 3 ^ 2` |
| $2^{(-3)}$ | `2 ^ (-3)` | `r 2 ^ (-3)` |
| $100^{1/2}$ | `100 ^ (1 / 2)` | `r 100 ^ (1 / 2)` |
| $\sqrt{100}$ | `sqrt(100)` | `r sqrt(100)` |
#### Mathematical Constants {-}
| Math | `R` code | Result |
|:------------:|:---------------:|:-----------------:|
| $\pi$ | `pi` | `r pi` |
| $e$ | `exp(1)` | `r exp(1)` |
#### Logarithms {-}
Note that we will use $\ln$ and $\log$ interchangeably to mean the natural logarithm. There is no `ln()` in `R`, instead it uses `log()` to mean the natural logarithm.
| Math | `R` code | Result |
|:------------:|:---------------:|:-----------------:|
| $\log(e)$ | `log(exp(1))` | `r log(exp(1))` |
| $\log_{10}(1000)$ | `log10(1000)` | `r log10(1000)` |
| $\log_{2}(8)$ | `log2(8)` | `r log2(8)` |
| $\log_{4}(16)$ | `log(16, base = 4)` | `r log(16, base = 4)` |
#### Trigonometry {-}
| Math | `R` code | Result |
|:------------:|:---------------:|:-----------------:|
| $\sin(\pi / 2)$ | `sin(pi / 2)` | `r sin(pi / 2)` |
| $\cos(0)$ | `cos(0)` | `r cos(0)` |
## Getting Help
In using `R` as a calculator, we have seen a number of functions: `sqrt()`, `exp()`, `log()` and `sin()`. To get documentation about a function in `R`, simply put a question mark in front of the function name, or call the function `help(function)` and RStudio will display the documentation, for example:
```{r, eval = FALSE}
?log
?sin
?paste
?lm
help(lm) # help() is equivalent
help(ggplot,package="ggplot2") # show help from a certain package
```
Frequently one of the most difficult things to do when learning `R` is asking for help. First, you need to decide to ask for help, then you need to know *how* to ask for help. Your very first line of defense should be to Google your error message or a short description of your issue. (The ability to solve problems using this method is quickly becoming an extremely valuable skill.) If that fails, and it eventually will, you should ask for help. There are a number of things you should include when contacting an instructor, or posting to a help website such as [Stack Overflow](https://stackoverflow.com).
- Describe what you expect the code to do.
- State the end goal you are trying to achieve. (Sometimes what you expect the code to do, is not what you want to actually do.)
- Provide the full text of any errors you have received.
- Provide enough code to recreate the error. Often for the purpose of this course, you could simply post your entire `.R` script or `.Rmd` to `slack`.
- Sometimes it is also helpful to include a screenshot of your entire RStudio window when the error occurs.
If you follow these steps, you will get your issue resolved much quicker, and possibly learn more in the process. Do not be discouraged by running into errors and difficulties when learning `R`. (Or any other technical skill.) It is simply part of the learning process.
## Installing Packages
`R` comes with a number of built-in functions and datasets, but one of the main strengths of `R` as an open-source project is its package system. Packages add additional functions and data. Frequently if you want to do something in `R`, and it is not available by default, there is a good chance that there is a package that will fulfill your needs.
To install a package, use the `install.packages()` function. Think of this as buying a recipe book from the store, bringing it home, and putting it on your shelf (i.e. into your library):
```{r, eval = FALSE}
install.packages("ggplot2")
```
Once a package is installed, it must be loaded into your current `R` session before being used. Think of this as taking the book off of the shelf and opening it up to read.
```{r, message = FALSE, warning = FALSE}
library(ggplot2)
```
Once you close `R`, all the packages are closed and put back on the imaginary shelf. The next time you open `R`, you do not have to install the package again, but you do have to load any packages you intend to use by invoking `library()`.
## `Code` vs Output in this Book {#code-output}
A quick note on styling choices in this book. We had to make a decision how to visually separate `R` code and resulting output in this book. All output lines are prefixed with `##` to make the distinction. A typical code snippet with output is thus going to look like this:
```{r}
1 + 3
# everything after a # is a comment, i.e. R disregards it.
```
where you see on the first line the `R` code, and on the second line the output. As mentioned, that line starts with `##` to say *this is an output*, followed by `[1]` (indicating this is a vector of length *one* - more on this below!), followed by the actual result - `1 + 3 = 4`!
Notice that you can simply copy and paste all the code you see into your `R` console. In fact, you are *strongly* encouraged to actually do this and try out **all the code** you see in this book.
Finally, please note that this way of showing output is fully our choice in this textbook, and that you should expect other output formats elsewhere. For example, in my `RStudio` console, the above code and output looks like this:
```R
> 1 + 3
[1] 4
```
## `ScPoApps` Package {#install-package}
To fully take advantage of our course, please install the associated `R` package directly from its online code repository. You can do this by copy and pasting the following three lines into your `R` console:
```R
if (!require("devtools")) install.packages("devtools")
devtools::install_github(repo = "ScPoEcon/ScPoApps")
```
In order to check whether everything works fine, you could load the library, and check it's current version:
```{r,warning=FALSE,message=FALSE,eval=FALSE}
library(ScPoApps)
packageVersion("ScPoApps")
```
## Data Types {#data-types}
`R` has a number of basic *data types*. While `R` is not a *strongly typed language* (i.e. you can be agnostic about types most of the times), it is useful to know what data types are available to you:
- Numeric
- Also known as Double. The default type when dealing with numbers.
- Examples: `1`, `1.0`, `42.5`
- Integer
- Examples: `1L`, `2L`, `42L`
- Complex
- Example: `4 + 2i`
- Logical
- Two possible values: `TRUE` and `FALSE`
- You can also use `T` and `F`, but this is *not* recommended.
- `NA` is also considered logical.
- Character
- Examples: `"a"`, `"Statistics"`, `"1 plus 2."`
- Categorical or `factor`
- A mixture of integer and character. A `factor` variable assigns a label to a numeric value.
- For example `factor(x=c(0,1),labels=c("male","female"))` assigns the string *male* to the numeric values `0`, and the string *female* to the value `1`.
## Data Structures
`R` also has a number of basic data *structures*. A data structure is either homogeneous (all elements are of the same data type) or heterogeneous (elements can be of more than one data type).
| Dimension | **Homogeneous** | **Heterogeneous** |
|:---------:|:---------------:|:-----------------:|
| 1 | Vector | List |
| 2 | Matrix | Data Frame |
| 3+ | Array | nested Lists |
### Vectors
Many operations in `R` make heavy use of **vectors**. A vector is a *container* for objects of identical type (see \@ref(data-types) above). Vectors in `R` are indexed starting at `1`. That is what the `[1]` in the output is indicating, that the first element of the row being displayed is the first element of the vector. Larger vectors will start additional rows with something like `[7]` where `7` is the index of the first element of that row.
Possibly the most common way to create a vector in `R` is using the `c()` function, which is short for "combine". As the name suggests, it combines a list of elements separated by commas. (Are you busy typing all of those examples into your `R` console? :-) )
```{r}
c(1, 3, 5, 7, 8, 9)
```
Here `R` simply outputs this vector. If we would like to store this vector in a **variable** we can do so with the **assignment** operator `=`. In this case the variable `x` now holds the vector we just created, and we can access the vector by typing `x`.
```{r}
x = c(1, 3, 5, 7, 8, 9)
x
```
As an aside, there is a long history of the assignment operator in `R`, partially due to the keys available on the [keyboards of the creators of the `S` language.](https://twitter.com/kwbroman/status/747829864091127809) (Which preceded `R`.) For simplicity we will use `=`, but know that often you will see `<-` as the assignment operator.
Because vectors must contain elements that are all the same type, `R` will automatically **coerce** (i.e. convert) to a single type when attempting to create a vector that combines multiple types.
```{r}
c(42, "Statistics", TRUE)
c(42, TRUE)
```
Frequently you may wish to create a vector based on a sequence of numbers. The quickest and easiest way to do this is with the `:` operator, which creates a sequence of integers between two specified integers.
```{r}
(y = 1:100)
```
Here we see `R` labeling the rows after the first since this is a large vector. Also, we see that by putting parentheses around the assignment, `R` both stores the vector in a variable called `y` and automatically outputs `y` to the console.
Note that scalars do not exists in `R`. They are simply vectors of length `1`.
```{r}
2
```
If we want to create a sequence that isn't limited to integers and increasing by 1 at a time, we can use the `seq()` function.
```{r}
seq(from = 1.5, to = 4.2, by = 0.1)
```
We will discuss functions in detail later, but note here that the input labels `from`, `to`, and `by` are optional.
```{r}
seq(1.5, 4.2, 0.1)
```
Another common operation to create a vector is `rep()`, which can repeat a single value a number of times.
```{r}
rep("A", times = 10)
```
The `rep()` function can be used to repeat a vector some number of times.
```{r}
rep(x, times = 3)
```
We have now seen four different ways to create vectors:
- `c()`
- `:`
- `seq()`
- `rep()`
So far we have mostly used them in isolation, but they are often used together.
```{r}
c(x, rep(seq(1, 9, 2), 3), c(1, 2, 3), 42, 2:4)
```
The length of a vector can be obtained with the `length()` function.
```{r}
length(x)
length(y)
```
```{block type="warning"}
Let's try this out! **Your turn**:
```
#### Task 1
1. Create a vector of five ones, i.e. `[1,1,1,1,1]`
1. Notice that the colon operator `a:b` is just short for *construct a sequence **from** `a` **to** `b`*. Create a vector the counts down from 10 to 0, i.e. it looks like `[10,9,8,7,6,5,4,3,2,1,0]`!
1. the `rep` function takes additional arguments `times` (as above), and `each`, which tells you how often *each element* should be repeated (as opposed to the entire input vector). Use `rep` to create a vector that looks like this: `[1 1 1 2 2 2 3 3 3 1 1 1 2 2 2 3 3 3]`
#### Subsetting
To subset a vector, i.e. to choose only some elements of it, we use square brackets, `[]`. Here we see that `x[1]` returns the first element, and `x[3]` returns the third element:
```{r}
x
x[1]
x[3]
```
We can also exclude certain indexes, in this case the second element.
```{r}
x[-2]
```
Lastly we see that we can subset based on a vector of indices.
```{r}
x[1:3]
x[c(1,3,4)]
```
All of the above are subsetting a vector using a vector of indexes. (Remember a single number is still a vector.) We could instead use a vector of logical values.
```{r}
z = c(TRUE, TRUE, FALSE, TRUE, TRUE, FALSE)
z
```
```{r}
x[z]
```
`R` is able to perform many operations on vectors and scalars alike:
```{r}
x = 1:10 # a vector
x + 1 # add a scalar
2 * x # multiply all elements by 2
2 ^ x # take 2 to the x as exponents
sqrt(x) # compute the square root of all elements in x
log(x) # take the natural log of all elements in x
x + 2*x # add vector x to vector 2x
```
We see that when a function like `log()` is called on a vector `x`, a vector is returned which has applied the function to each element of the vector `x`.
### Logical Operators
| Operator | Summary | Example | Result |
|:---------|:---------------------:|:---------------------:|:-------:|
| `x < y` | `x` less than `y` | `3 < 42` | `r 3 < 42` |
| `x > y` | `x` greater than `y` | `3 > 42` | `r 3 > 42` |
| `x <= y` | `x` less than or equal to `y` | `3 <= 42` | `r 3 <= 42` |
| `x >= y` | `x` greater than or equal to `y` | `3 >= 42` | `r 3 >= 42` |
| `x == y` | `x`equal to `y` | `3 == 42` | `r 3 == 42` |
| `x != y` | `x` not equal to `y` | `3 != 42` | `r 3 != 42` |
| `!x` | not `x` | `!(3 > 42)` | `r !(3 > 42)` |
| `x | y` | `x` or `y` | `(3 > 42) | TRUE` | `r (3 > 42) | TRUE` |
| `x & y` | `x` and `y` | `(3 < 4) & ( 42 > 13)` | `r (3 < 4) & ( 42 > 13)` |
In `R`, logical operators also work on vectors:
```{r}
x = c(1, 3, 5, 7, 8, 9)
```
```{r}
x > 3
x < 3
x == 3
x != 3
```
```{r}
x == 3 & x != 3
x == 3 | x != 3
```
This is quite useful for subsetting.
```{r}
x[x > 3]
x[x != 3]
```
```{r}
sum(x > 3)
as.numeric(x > 3)
```
Here we saw that using the `sum()` function on a vector of logical `TRUE` and `FALSE` values that is the result of `x > 3` results in a numeric result: you just *counted* for how many elements of `x`, the condition `> 3` is `TRUE`. During the call to `sum()`, `R` is first automatically coercing the logical to numeric where `TRUE` is `1` and `FALSE` is `0`. This coercion from logical to numeric happens for most mathematical operations.
```{r}
# which(condition of x) returns true/false
# each index of x where condition is true
which(x > 3)
x[which(x > 3)]
max(x)
which(x == max(x))
which.max(x)
```
#### Task 2
1. Create a vector filled with 10 numbers drawn from the uniform distribution (hint: use function `runif`) and store them in `x`.
1. Using logical subsetting as above, get all the elements of `x` which are larger than 0.5, and store them in `y`.
1. using the function `which`, store the *indices* of all the elements of `x` which are larger than 0.5 in `iy`.
1. Check that `y` and `x[iy]` are identical.
### Matrices
`R` can also be used for **matrix** calculations. Matrices have rows and columns containing a single data type. In a matrix, the order of rows and columns is important. (This is not true of *data frames*, which we will see later.)
Matrices can be created using the `matrix` function.
```{r}
x = 1:9
x
X = matrix(x, nrow = 3, ncol = 3)
X
```
Notice here that `R` is case sensitive (`x` vs `X`).
By default the `matrix` function fills your data into the matrix column by column. But we can also tell `R` to fill rows instead:
```{r}
Y = matrix(x, nrow = 3, ncol = 3, byrow = TRUE)
Y
```
We can also create a matrix of a specified dimension where every element is the same, in this case `0`.
```{r}
Z = matrix(0, 2, 4)
Z
```
Like vectors, matrices can be subsetted using square brackets, `[]`. However, since matrices are two-dimensional, we need to specify both a row and a column when subsetting.
```{r}
X
X[1, 2]
```
Here we accessed the element in the first row and the second column. We could also subset an entire row or column.
```{r}
X[1, ]
X[, 2]
```
We can also use vectors to subset more than one row or column at a time. Here we subset to the first and third column of the second row:
```{r}
X[2, c(1, 3)]
```
Matrices can also be created by combining vectors as columns, using `cbind`, or combining vectors as rows, using `rbind`.
```{r}
x = 1:9
rev(x)
rep(1, 9)
```
```{r}
rbind(x, rev(x), rep(1, 9))
```
```{r}
cbind(col_1 = x, col_2 = rev(x), col_3 = rep(1, 9))
```
When using `rbind` and `cbind` you can specify "argument" names that will be used as column names.
`R` can then be used to perform matrix calculations.
```{r}
x = 1:9
y = 9:1
X = matrix(x, 3, 3)
Y = matrix(y, 3, 3)
X
Y
```
```{r}
X + Y
X - Y
X * Y
X / Y
```
Note that `X * Y` is **not** matrix multiplication. It is *element by element* multiplication. (Same for `X / Y`).
Matrix multiplication uses `%*%`. Other matrix functions include `t()` which gives the transpose of a matrix and `solve()` which returns the inverse of a square matrix if it is invertible.
```{r}
X %*% Y
t(X)
```
### Arrays
A vector is a one-dimensional array. A matrix is a two-dimensional array. In `R` you can create arrays of arbitrary dimensionality `N`. Here is how:
```{r}
d = 1:16
d3 = array(data = d,dim = c(4,2,2))
d4 = array(data = d,dim = c(4,2,2,3)) # will recycle 1:16
d3
```
You can see that `d3` are simply *two* (4,2) matrices laid on top of each other, as if there were *two pages*. Similary, `d4` would have two pages, and another 3 registers in a fourth dimension. And so on.
You can subset an array like you would a vector or a matrix, taking care to index each dimension:
```{r}
d3[ ,1,1] # all elements from col 1, page 1
d3[2:3, , ] # rows 2:3 from all pages
d3[2,2, ] # row 2, col 2 from both pages.
```
#### Task 3
1. Create a vector containing `1,2,3,4,5` called v.
1. Create a (2,5) matrix `m` containing the data `1,2,3,4,5,6,7,8,9,10`. The first row should be `1,2,3,4,5`.
1. Perform matrix multiplication of `m` with `v`. Use the command `%*%`. What dimension does the output have?
1. Why does `v %*% m` not work?
### Lists
A list is a one-dimensional *heterogeneous* data structure. So it is indexed like a vector with a single integer value (or with a name), but each element can contain an element of any type. Lists are similar to a python or julia `Dict` object. Many `R` structures and outputs are lists themselves. Lists are extremely useful and versatile objects, so make sure you understand their useage:
```{r}
# creation without fieldnames
list(42, "Hello", TRUE)
# creation with fieldnames
ex_list = list(
a = c(1, 2, 3, 4),
b = TRUE,
c = "Hello!",
d = function(arg = 42) {print("Hello World!")},
e = diag(5)
)
```
Lists can be subset using two syntaxes, the `$` operator, and square brackets `[]`. The `$` operator returns a named **element** of a list. The `[]` syntax returns a **list**, while the `[[]]` returns an **element** of a list.
- `ex_list[1]` returns a list contain the first element.
- `ex_list[[1]]` returns the first element of the list, in this case, a vector.
```{r}
# subsetting
ex_list$e
ex_list[1:2]
ex_list[1]
ex_list[[1]]
ex_list[c("e", "a")]
ex_list["e"]
ex_list[["e"]]
ex_list$d
ex_list$d(arg = 1)
```
#### Task 4
1. Copy and paste the above code for `ex_list` into your R session. Remember that `list` can hold any kind of `R` object. Like...another list! So, create a new list `new_list` that has two fields: a first field called "this" with string content `"is awesome"`, and a second field called "ex_list" that contains `ex_list`.
1. Accessing members is like in a plain list, just with several layers now. Get the element `c` from `ex_list` in `new_list`!
1. Compose a new string out of the first element in `new_list`, the element under label `this`. Use the function `paste` to print `R is awesome` to your screen.
## Data Frames {#dataframes}
We have previously seen vectors and matrices for storing data as we introduced `R`. We will now introduce a **data frame** which will be the most common way that we store and interact with data in this course. A `data.frame` is similar to a python `pandas.dataframe` or a julia `DataFrame`. (But the `R` version was the first! :-) )
```{r}
example_data = data.frame(x = c(1, 3, 5, 7, 9, 1, 3, 5, 7, 9),
y = c(rep("Hello", 9), "Goodbye"),
z = rep(c(TRUE, FALSE), 5))
```
Unlike a matrix, which can be thought of as a vector rearranged into rows and columns, a data frame is not required to have the same data type for each element. A data frame is a **list** of vectors, and each vector has a *name*. So, each vector must contain the same data type, but the different vectors can store different data types. Note, however, that all vectors must have **the same length** (differently from a `list`)!
```{block, type="tip"}
A **data.frame** is similar to a typical Spreadsheet. There are *rows*, and there are *columns*. A row is typically thought of as an *observation*, and each column is a certain *variable*, *characteristic* or *feature* of that observation.
```
<br>
Let's look at the data frame we just created above:
```{r}
example_data
```
Unlike a list, which has more flexibility, the elements of a data frame must all be vectors. Again, we access any given column with the `$` operator:
```{r}
example_data$x
all.equal(length(example_data$x),
length(example_data$y),
length(example_data$z))
str(example_data)
nrow(example_data)
ncol(example_data)
dim(example_data)
names(example_data)
```
### Working with `data.frames`
The `data.frame()` function above is one way to create a data frame. We can also import data from various file types in into `R`, as well as use data stored in packages.
```{r, echo = FALSE}
write.csv(example_data, "data/example-data.csv", row.names = FALSE)
write.csv(example_data,"inst/datasets/example-data.csv", row.names=FALSE)
```
To read this data back into `R`, we will use the built-in function `read.csv`:
```{r, message = FALSE, warning = FALSE}
path = system.file(package="ScPoEconometrics","datasets","example-data.csv")
example_data_from_disk = read.csv(path)
```
This particular line of code assumes that you installed the associated R package to this book, hence you have this dataset stored on your computer at `system.file(package = "ScPoEconometrics","datasets","example-data.csv")`.
```{r}
example_data_from_disk
```
When using data, there are three things we would generally like to do:
- Look at the raw data.
- Understand the data. (Where did it come from? What are the variables? Etc.)
- Visualize the data.
To look at data in a `data.frame`, we have two useful commands: `head()` and `str()`.
```{r}
# we are working with the built-in mtcars dataset:
mtcars
```
You can see that this prints the entire data.frame to screen. The function `head()` will display the first `n` observations of the data frame.
```{r}
head(mtcars,n=2)
head(mtcars) # default
```
The function `str()` will display the "structure" of the data frame. It will display the number of **observations** and **variables**, list the variables, give the type of each variable, and show some elements of each variable. This information can also be found in the "Environment" window in RStudio.
```{r}
str(mtcars)
```
In this dataset an observation is for a particular model of a car, and the variables describe attributes of the car, for example its fuel efficiency, or its weight.
To understand more about the data set, we use the `?` operator to pull up the documentation for the data.
```{r, eval = FALSE}
?mtcars
```
`R` has a number of functions for quickly working with and extracting basic information from data frames. To quickly obtain a vector of the variable names, we use the `names()` function.
```{r}
names(mtcars)
```
To access one of the variables **as a vector**, we use the `$` operator.
```{r}
mtcars$mpg
mtcars$wt
```
We can use the `dim()`, `nrow()` and `ncol()` functions to obtain information about the dimension of the data frame.
```{r}
dim(mtcars)
nrow(mtcars)
ncol(mtcars)
```
Here `nrow()` is also the number of observations, which in most cases is the *sample size*.
Subsetting data frames can work much like subsetting matrices using square brackets, `[ , ]`. Here, we find vehicles with mpg over 25 miles per gallon and only display columns `cyl`, `disp` and `wt`.
```{r}
# mpg[row condition, col condition]
mtcars[mtcars$mpg > 20, c("cyl", "disp", "wt")]
```
An alternative would be to use the `subset()` function, which has a much more readable syntax.
```{r, eval = FALSE}
subset(mtcars, subset = mpg > 25, select = c("cyl", "disp", "wt"))
```
#### Task 5
1. How many observations are there in `mtcars`?
1. How many variables?
1. What is the average value of `mpg`?
1. What is the average value of `mpg` for cars with more than 4 cylinders, i.e. with `cyl>4`?
## Programming Basics
In this section we illustrate some general concepts related to programming.
### Variables
We encountered the term *variable* already several times, but mainly in the context of a column of a data.frame. In programming, a variable is denotes an *object*. Another way to say it is that a variable is a name or a *label* for something:
```{r}
x = 1
y = "roses"
z = function(x){sqrt(x)}
```
Here `x` refers to the value `1`, `y` holds the string "roses", and `z` is the name of a function that computes $\sqrt{x}$. Notice that the argument `x` of the function is different from the `x` we just defined. It is **local** to the function:
```{r}
x
z(9)
```
### Control Flow
Control Flow relates to ways in which you can adapt your code to different circumstances. Based on a `condition` being `TRUE`, your program will do one thing, as opposed to another thing. This is most widely known as an `if/else` statement. In `R`, the if/else syntax is:
```{r, eval = FALSE}
if (condition = TRUE) {
some R code
} else {
some other R code
}
```
For example,
```{r}
x = 1
y = 3
if (x > y) { # test if x > y
# if TRUE
z = x * y
print("x is larger than y")
} else {
# if FALSE
z = x + 5 * y
print("x is less than or equal to y")
}
z
```
### Loops
Loops are a very important programming construct. As the name suggests, in a *loop*, the programming *repeatedly* loops over a set of instructions, until some condition tells it to stop. A very powerful, yet simple, construction is that the program can *count how many steps* it has done already - which may be important to know for many algorithms. The syntax of a `for` loop (there are others), is
```{r eval=FALSE}
for (ix in 1:10){ # does not have to be 1:10!
# loop body: gets executed each time
# the value of ix changes with each iteration
}
```
For example, consider this simple `for` loop, which will simply print the value of the *iterator* (called `i` in this case) to screen:
```{r}
for (i in 1:5){
print(i)
}
```
Notice that instead of `1:5`, we could have *any* kind of iterable collection:
```{r}
for (i in c("mangos","bananas","apples")){
print(paste("I love",i)) # the paste function pastes together strings
}
```
We often also see *nested* loops, which are just what its name suggests:
```{r}
for (i in 2:3){
# first nest: for each i
for (j in c("mangos","bananas","apples")){
# second nest: for each j
print(paste("Can I get",i,j,"please?"))
}
}
```
The important thing to note here is that you can do calculations with the iterators *while inside a loop*.
### Functions
So far we have been using functions, but haven't actually discussed some of their details. A function is a set of instructions that `R` executes for us, much like those collected in a script file. The good thing is that functions are much more flexible than scripts, since they can depend on *input arguments*, which change the way the function behaves. Here is how to define a function:
```{r eval=FALSE}
function_name <- function(arg1,arg2=default_value){
# function body
# you do stuff with arg1 and arg2
# you can have any number of arguments, with or without defaults
# any valid `R` commands can be included here
# the last line is returned
}
```
And here is a trivial example of a function definition:
```{r}
hello <- function(your_name = "Lord Vader"){
paste("You R most welcome,",your_name)
# we could also write:
# return(paste("You R most welcome,",your_name))
}
# we call the function by typing it's name with round brackets
hello()
```
You see that by not specifying the argument `your_name`, `R` reverts to the default value given. Try with your own name now!
Just typing the function name returns the actual definition to us, which is handy sometimes:
```{r}
hello
```
It's instructive to consider that before we defined the function `hello` above, `R` did not know what to do, had you called `hello()`. The function did not exist! In this sense, we *taught `R` a new trick*. This feature to create new capabilities on top of a core language is one of the most powerful characteristics of programming languages. In general, it is good practice to split your code into several smaller functions, rather than one long script file. It makes your code more readable, and it is easier to track down mistakes.
#### Task 6
1. Write a for loop that counts down from 10 to 1, printing the value of the iterator to the screen.
1. Modify that loop to write "i iterations to go" where `i` is the iterator
1. Modify that loop so that each iteration takes roughly one second. You can achieve that by adding the command `Sys.sleep(1)` below the line that prints "i iterations to go".