-
Notifications
You must be signed in to change notification settings - Fork 1
/
bootcamp-r-series-010-intro-to-r-pt1.Rmd
574 lines (438 loc) · 19.2 KB
/
bootcamp-r-series-010-intro-to-r-pt1.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
---
title: "Introduction to R: Part One"
output:
html_document: default
---
To learn everything there is to know about R, [read the docs](https://cran.r-project.org/doc/manuals/R-lang.html). To learn just enough to be dangerous, follow along :)
## Introductions and Overview
This workshop serves as a gentle introduction to programming with R, with a focus on application to data science and research. We will cover the basics of R, such as using the command line as a calculator, working with variables, simple data structures, and data types. We will show how to load data sets into R, and how to summarize data with statistics and plots. At the end we will also discuss some considerations when choosing R over other programming languages like Python or SPSS.
## Opening the R command line
- The R command line interface (CLI) is a simple interface for entering R commands
- A *command* is a way of giving the computer some information and having it perform a task
### Open in Windows
- start menu (see video below)
- desktop shortcut
- task bar shortcut
<video width="100%" autoplay muted loop controls>
<source src="media/vid/01-opening-r-gui.webm" type="video/webm">
</video>
### Open in Linux
- application menu
- dock shortcut
- terminal (see video below)
<video width="100%" autoplay muted loop controls>
<source src="media/vid/01-opening-r-cli.webm" type="video/webm">
</video>
## Using the console as a calculator
### Basic arithmetic operators
| Operator | Description | Example |
| :---------- | :----------------| :-------------- |
| `+` | addition | `3 + 4 = 7` |
| `-` | subtraction | `10 - 2 = 8` |
| `*` | multiplication | `2.5 * 4 = 10` |
| `/` | division | `9 / 2 = 4.5` |
| `^` | exponentiation | `11^2 = 121` |
| `%%` | modulus | `5 %% 3 = 2` |
| `%/%` | integer division | `9 %/% 2 = 4` |
```{r 010-dental-mammal}
# Order of operations still applies
5 - 4 + 5*2^4
# Use parentheses to ensure desired order of operations
(-2 + (5 / 3.8)) * 1.618^2
```
### Three basic types of numbers
I say there are three types of numbers in R because R has different ways of working with different numbers
| Number type | Description | Example |
| :---------- | :------------------------------------------------------------------------- | :-------------- |
| Integer | Whole numbers, positive or negative | `4L, -3L, 0L` |
| Decimal | Any number, positive or negative, with a fractional part | `3.1, pi, 4.0` |
| Complex | A real decimal number with an imaginary decimal part | `-2.1+5i` |
Notice that the integers have an `L` at the end. This is to explicitly tell R to represent a number as a [[long](https://en.wikipedia.org/wiki/Integer_(computer_science)#Long_integer)] integer, rather than a double (decimal) number.
```{r 010-noted-citron}
is.integer(4) # FALSE
is.double(4) # TRUE
is.integer(4L) # TRUE
```
### Logical operators
Logical operators test for a condition. They ask a question, and the answer is either `TRUE` or `FALSE`.
| Operator | Description | Example |
| :---------- | :------------------------------------------------------------------------- | :-------------- |
| `<` | less than | `5 < 4 -> FALSE` |
| `<=` | less than or equal | `6 <= 6 -> TRUE` |
| `>` | greater than | `Inf > 1e6 -> TRUE` |
| `>=` | greater than or equal | `3.5 >= 9 -> FALSE` |
| `==` | exactly equal | `sin(0) == 0 -> TRUE` |
| `!=` | not equal | `(3+1)^2 != 3^2 + 1^1 -> TRUE` |
| `!` | not | `!TRUE -> FALSE` |
| `&&` | and (short-circuiting) | `(5 < 7) && (7 < 10) -> TRUE` |
| \` | | \` |
| `&` | and (vectorized) | `TRUE & 2 > c(1,2,3) -> c(FALSE, FALSE, TRUE)` |
| \` | \` | or (vectorized) |
### Other math functions
| Function | Description | Example |
| :---------- | :------------------------------------------------------------------------- | :-------------- |
| `abs` | absolute value of a number | `abs(-2.5), abs(3L), abs(3+4i)` |
| `sqrt` | square root of a number | `sqrt(0.81), sqrt(-1+0i)` |
| `exp` | $e^x$ | `exp(1) ->` `r exp(1)` |
| `log` | logarithm of a number (base is the natural number $e$ by default) | |
| `log10` | base 10 logarithm of a number (see also `log2`, `log1p`, `logb`) | |
| `sin`, `cos`, `tan` | basic trigonometric functions (radians by default) | |
| `asin`, `acos`, `atan` | inverse trigonometric functions | |
| `sinh`, `asinh`, etc. | hyperbolic and inverse hyperbolic trigonometric functions | |
| `ceiling` | rounds a number towards infinity | `ceiling(-2.8) -> -2` |
| `floor` | rounds a number towards negative infinity | `floor(3.9) -> 3` |
| `round` | rounds a number to a specified number of digits (round to even by default) | |
| `trunc` | strips the decimal part from a number | `trunc(2.1) -> 2`, `trunc(2.9) -> 2` |
Also note, all *infix* operations can be used with *prefix* notation:
```{r 010-near-whippet}
3 + 4 # infix
`+`(3, 4) # prefix
```
### Built-in constants and other values
| Keyword | Description | Example |
| :---------- | :-----------------------------------------------------| :----------------|
| `Inf` | The floating point representation of infinity | `1 / 0 -> Inf` |
| `-Inf` | Negative infinity | `1 / -0 -> -Inf` |
| `NaN` | **N**ot **a** **N**umber | `0 / 0 -> NaN` |
| `NA` | A placeholder for missing values | |
| `NULL` | An R object representing the empty set or nothing | |
| `pi` | The ratio of a circle's circumference to its diameter | `3.14159...` |
The *Institute of Electrical and Electronics Engineers* (IEEE, "eye-triple-ee") sets many of the standards for computer protocol, including how *floating point* numbers behave. A floating point number is the computer representation of a real number, but due to finite precision, there are some inconsistencies:
```{r 010-several-peacock}
0.3 - 0.1 # should be 0.2
(0.3 - 0.1) == 0.2 # should be true
# R is lying to us!
print(0.3-0.1, digits = 20)
# use `all.equal` to test floating point equality
all.equal(0.3 - 0.1, 0.2)
```
- R uses 64 bit (double) precision for floating point numbers and 32 bit *signed* integers
- [https://en.wikipedia.org/wiki/IEEE_754](https://en.wikipedia.org/wiki/IEEE_754)
- [https://en.wikipedia.org/wiki/Division_by_zero#Computer_arithmetic](https://en.wikipedia.org/wiki/Division_by_zero#Computer_arithmetic)
### Practice
The quadratic equation is used to find the roots of quadratic (2nd degree) polynomials. For a quadratic polynomial given by
$$
ax^2 + bx + c
$$
the roots are given by
$$
x_{1,2} = \frac{-b \pm \sqrt{b^2 -4ac}}{2a}
$$
Find the roots of the following equations using the quadratic equation:
a) $y = 2x^2 + 2x - 24$
b) $y = 4x^2 + 9$
c) $y = x^2 + 4x + 4$
## Accessing the built-in docs
Most if not all functions in R have useful help documentation that can be accessed directly within the R console.
```r
> help(sum)
> ?sum
> library(help = "base")
```
## Working with variables
- Let you store a number or other object in the *environment* list
- Similar to "memory recall" of a calculator, but better
To create a new variable, we can use *left* or *right* assignment:
```{r 010-youthful-mochi}
# left assignment
x <- 10
# right assignment
"some string" -> y
```
- You can use an "equal sign" for assignment, but it is discouraged
To list all variables in the session (environment), do:
```{r 010-united-piranha}
# list all variables in the environment
ls()
```
We can see what is stored in those variables by typing them into the console:
```{r 010-informal-stomach}
# show what is stored in the variables
x
y
```
**Good variable naming conventions (in R)**
- See the [tidyverse style guide](https://style.tidyverse.org/syntax.html#object-names) for a full rundown of object naming
- let your names be meaningful
- let your names be consistent
- avoid using existing function names (e.g. `mean`, `c`) and objects (e.g. `T`, `F`, `pi`)
- List of reserved words in R: [https://cran.r-project.org/doc/manuals/R-lang.html#Reserved-words](https://cran.r-project.org/doc/manuals/R-lang.html#Reserved-words)
- avoid using dots
- use the existing conventions of whatever project you are contributing to
## Basic data types in R
```{r 010-bubbly-bake}
# logical (boolean)
typeof(TRUE)
# integer
typeof(5L) # note the 'L' at the end
# double
typeof(6.3)
typeof(4) # no 'L' at the end --> double
# complex
typeof(3 + 2i)
# character
typeof("hello world")
```
## Working with different data types
*Coercion and conversion*
- R will always coerce (convert) an object to the least restrictive type
```{r 010-misty-earthworm}
typeof(TRUE + 3L)
typeof(TRUE + 3.0)
typeof(TRUE + 3 + 0i)
```
Guess the output type
```{r 010-impish-mealworm}
# a "regular" number
14
# integer division
14 %/% 3
# remainder
14 %% 3
# ceiling/floor/round
ceiling(pi)
round(pi)
```
How can we ensure the output type of an operation? Most of the time it's okay to let R worry about the *return* types. In other situations, there's the `as` command:
```{r 010-skinny-raccoon}
as.integer(4.0)
as.logical(4L) # any non-zero value is true
as.complex(4)
as.double("3.14159")
```
Careful, as not every value can be coerced to every other type, or no robust checks will be performed to ensure validity of a conversion:
```{r 010-advanced-python}
# converts to an integer via truncation
as.integer(4.5)
```
*Testing for types*
We can use the `is` command to ask R what the type of an object is:
```{r 010-gaseous-sushi}
is.integer(4L)
is.double(3+2i)
is.numeric(4)
is.numeric(4L)
is.numeric(4+2i)
```
Sometimes a thing that looks like an integer is really a double:
```{r 010-cerulean-glasses}
# actually a double
x <- 4
is.integer(x)
```
How to check that a number is an integer:
```{r 010-sticky-currants}
as.integer(x) == x
```
## Special data type: Factors
A factor *looks* like a string, but *acts* like an integer (most of the time).
```{r 010-basic-dinosaur}
# most often used for categorical observations
pets <- c("cat", "dog", "lizard", "raccoon")
(pet_obs <- sample(pets, 20, TRUE))
# Turn the character vector into a set of factors
pet_fct <- factor(pet_obs)
pet_fct
# can be converted to an integer vector
as.integer(pet_fct)
# can be converted to a character vector
as.character(pet_fct)
```
## Overview of objects and data structures
For a full overview, see the [R documentation on basic types](https://cran.r-project.org/doc/manuals/R-lang.html#Basic-types).
- Vectors
- Matrices and Arrays
- Lists
- Compound objects
- Factors
- Data frames
## Working with vectors, matrices, and arrays
### Vectors
- a *vector* is a collection of *same-type* objects
- aka an *atomic* vector
- all elements coerced to the least restrictive type
- typically created using the *concatenate* command, `c()`
```{r 010-valid-savory, results="hold"}
# a few vectors
c(4.5, 2, 3.8)
1:4
c(TRUE, FALSE, FALSE)
seq(from = 0.1, to = 1.0, by = 0.4)
LETTERS
```
**Question:** What is meant by "least restrictive type"?
```{r 010-secret-tick}
# mix of integer and logical
c(TRUE, 5L, -2L, FALSE)
# mix of integer and double
c(5L, pi, -7L, 2.2)
# mix of double and complex
c(pi, -2+7i, 6.9, -3.5i)
# mix of double and character
c("asdf", 6.12, pi, "3")
```
We can access the elements of a vector by using brackets: `[]`. Note that R uses "one-based indexing", meaning that arrays start at $1$, not $0$.
```{r 010-fine-nosh}
# accessing a single element from `letters`
letters[4]
# accessing multiple elements using a vector of indices
letters[c(1, 3, 5)]
# accessing a subset using conditionals
x <- 1:10
x[x < 4]
# accessing the last element
tail(letters, n = 1)
letters[length(letters)]
```
### Matrices
- A matrix in R is a vector with a `dim` *attribute*
- It is stored in memory the same way as a vector is
```{r 010-shamrock-roast}
# creating a matrix using the `matrix()` function
matrix(1:12, nrow = 3, ncol = 4)
# filling a matrix with a single value
matrix("m", nrow = 5, ncol = 2)
```
Matrices (and vectors and arrays) are stored in *column-major order*
```{r 010-dearest-fried}
# default: fills in down each column
matrix(1:12, nrow = 3)
# explicitly fill in accross rows first
matrix(1:12, nrow = 3, byrow = TRUE)
```
Elements of a matrix can either be accessed with row-column pairs, or with *linear indexing*
```{r 010-bruised-jimmies}
# create a 3x5 matrix
(M <- matrix(1:15, nrow = 3))
# get the element at the second row and fourth column
M[2, 4]
# get the 8th element in memory
M[8]
```
You can create subsets of a matrix using a pair of vectors for indices.
```{r 010-cloudy-picnic}
# get rows 1 and 3, and columns 2 and 4
M[c(1, 3), c(2, 4)]
```
A matrix can be turned back into a vector by removing its dimension attribute. In the same way, a matrix can be reshaped, or a vector can be turned into a matrix.
```{r 010-grubby-arachnid}
# show the attributes of the matrix, M
attributes(M)
# get the `dim` attribute
attr(M, "dim")
# remove the `dim` attribute by setting it to `NULL`
attr(M, "dim") <- NULL
M
# turn M into a 5x3 matrix
attr(M, "dim") <- c(5, 3)
M
```
### Arrays
- An array is an extension of a matrix, having 2 or more dimensions
- Arrays are created using the `array()` function or by setting the `dim` attribute of a vector
```{r 010-muddy-savory}
# one array
(a <- array(1:(5*4*3), dim = c(5, 4, 3)))
# show the attributes
attributes(a)
```
## Working with lists
- A list is a "generic vector"
- Each element of a list can be *any* type of R object
```{r 010-scrawny-nosh}
(L <- list(a = 1, "d", formula(y ~ x), sublist = list(a = 1, b = 1:4, c = letters[3:7])))
```
As seen above, lists can hold other lists, and elements can be named or referenced by index. This can become complicated to mentally parse as printed above, so the `str` command can come in handy.
```{r 010-jumpy-pudding}
str(L)
```
Elements of a list can be accessed in three different ways.
```{r 010-witty-porpoise}
# Using single bracket notation. Returns a list containing the object at this index.
L[1]
# Using the `$` selector. Returns the object at this index.
L$a
# Using double bracket notation. Returns the object at this index.
L[[1]]
```
## Working with data frames
What are some of the key properties of a data frame?
- Two dimensional (tabular)
- Can be a mix of numeric, logical, and character (and more) types
- All columns are the same length
*A data frame is essentially a list with a few extra restrictions*
Accessing elements of a data frame is similar to lists *and* matrices.
```{r 010-violet-daikon}
# getting a single column using the `$` selector or `[[`
mtcars$mpg # column "mpg"
mtcars[["mpg"]] # column "mpg"
# getting multiple columns using `[` and a index/character vector
mtcars["mpg"] # a new data frame with just the "mpg" column
mtcars[1:3] # columns 1 through 3
# getting a single element using `[`
mtcars[1, 3] # row 1, col 3 ("disp")
# getting a single element using `$` and `[`
mtcars$disp[1] # row 1, col 3 ("disp")
```
## Reading data from a file
Common text files can be read using the `read-` set of functions
- read comma separated values (CSV) files with `read.csv()`
- the more general function is `read.delim()`
- the other specialized function is `read.table()`
- read general text files using `readLines()`
```{r 010-colorful-almond}
# read in the sample csv file
df <- read.csv("data/simple_csv.csv")
df
```
More proprietary formats can be read in using a library
- `readr` for the tidyverse version of `read-` functions
- `readxl` for Excel spreadsheets
- `R.matlab` for Matlab files
## Fitting a linear model
R has built-in support for fitting \[generalized\] linear models, with support for numeric and factor variables.
```{r 010-radiant-mussels}
# y ~ normal(3x + 2, 0.5)
x <- rnorm(30)
y <- rnorm(length(x), 3*x + 2, 0.5)
plot(y ~ x) # same as plot(x, y)
# fit a linear model
lm(y ~ x) # slope-intercept model. Same as `lm(y ~ 1 + x)`
lm(y ~ 0 + x) # slope only model (no intercept)
```
Can also fit a generalized linear model using (you guessed it) the `glm()` function.
```{r 010-cheap-jelly}
# logit(theta) = 3x + 2
k <- rbinom(length(x), size = 1, prob = plogis(3*x+2))
plot(k ~ x)
# fit a generalized linear model with logit link
glm(k ~ 1 + x, family = binomial(link = "logit"))
```
## Summarizing data frames and models
R has a method for summarizing vectors, data frames, and fitted models, and it is the `summary()` function.
```{r 010-husky-caribou}
# summarize a numeric vector
z <- rnorm(50)
summary(z)
# summarize a data frame
df <- data.frame(a = 1L:10L, b = rexp(10), c = factor(sample(c("a", "b", "c"), 10, TRUE)))
summary(df)
# summarize a linear model
fit <- lm(y ~ 1 + x)
summary(fit)
```
Notice that it outputs differently for different input objects. This is because `summary()` is a *generic* function, meaning that it has multiple *methods* defined for different R objects, and packages can define their own behavior for their own types.
## Producing simple plots
There are a few simple plotting functions in R
- `plot()`
- also "generic"
- can produce scatter and line plots
- `lines()` adds lines to plots
- `points()` adds points to plots
- `curve()` plots a function over a domain
- can be used alone or "layered" on top of an existing plot
Other types of graphs include
- `hist()` for histograms
- `barplot()`
- `boxplot()`
- `stem()` for stem-and-leaf plot