/
intro_to_R.Rpres
646 lines (537 loc) · 19 KB
/
intro_to_R.Rpres
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
<style>
.small-code pre code {
font-size: 1em;
}
</style>
Introduction to R
========================================================
author: Bruce Bugbee
date: August 17, 2017
autosize: true
A little about me...
========================================================
- Computational Statistician at National Renewable Energy Lab
- R user for about 10 years now
- Probably needs more coffee at the moment...
What Is R?
========================================================
![Rlogo](img/Rlogo.svg)
***
- "R is a free software environment for statistical computing and graphics." -- www.r-project.org
- "R is, at its heart, an elegant and beautiful language, well tailored for data analysis and statistics." -- Hadley Wickham in __Advanced R__
- "R is that thing my advisor told me to use. Will you please stop bothering me and just help me with my stats?" -- Most grad students
What Is R?
========================================================
- Free, open source, and widely supported
- An object oriented programming language with historical ties to C
- Focueses on data analysis, modeling, and visualization first and foremost
- Most common research language for cutting edge statistics (fights with Python/Scala for machine learning community)
Goal of this talk
========================================================
My goal here is to provide some concrete examples of the foundational elements of R including I/O, data types, control flow, statistical modeling, and visualization.
The repo with all code, examples, and slides can be found here: [https://github.com/BruceBugbee/rmacc-hpc-2017](https://github.com/BruceBugbee/rmacc-hpc-2017)
Data Classes
========================================================
R has numerous built in classes for different data types.
- double
- integer
- character
- boolean
- factor
- Date
- DateTime
- complex
- ...
Doubles
========================================================
Standard double precision class. A historical anomaly often calls this "numeric" instead of "double".
```{r}
class(43)
```
Integer
========================================================
Seldom used in most day to day R analysis. Integer classes come more into play when you are paying attention to memory issues.
```{r}
class(4) #numeric
class(4L) #integer
```
Character
========================================================
Characters are defined using double or single quotes.
```{r}
class("pineapple")
class("8675309")
class(8675309)
```
Boolean
========================================================
Binary true/false objects.
```{r}
class(T) #two acceptable ways
class(TRUE)
```
Four Basic Objects
========================================================
These are the four foundational data types in R. They all have a couple common methods for defining, coercing, or checking class type
Coercing objects
========================================================
All these types have functions prefaced with __as.__ that try to coerce from one type to another.
```{r}
as.character(100)
as.character(100L)
as.character(TRUE)
```
Coercing objects
========================================================
```{r}
as.numeric(100L)
as.numeric("100")
as.numeric(TRUE) #codes to 1 for True, 0 for False
```
Coercing objects
========================================================
```{r}
as.logical("TRUE")
as.logical("T")
as.logical("True")
as.logical("pineapple")
```
Checking class
========================================================
To check whether an object is of a certain class, use the prebuilt function that has the __is.__ prefix.
```{r}
is.logical(TRUE)
is.numeric(100L) #notice how numeric will pass integers with no problem
is.double(100L)
is.character("pineapple")
```
Data Structures
========================================================
One of the primary strengths of R is that its built in data structures are designed to handle statistical and scientific computing problems
Vectors
========================================================
Vectors are 1-dimensional collections of objects with the same class and a fixed length property.
```{r vectors}
vec <- c(1, 2, 3, 4, 5, 6)
print(vec)
vec[1]
vec[0] #R indices start at 1, not 0
class(vec)
```
Vectors
========================================================
Vectors are 1-dimensional collections of objects with the same class and a fixed length property.
```{r vectors2}
vec <- LETTERS[1:8]
print(vec)
vec[1]
class(vec)
```
Vectors
========================================================
The __length__ function is pretty self explanatory
```{r }
vec
length(vec)
```
Vectors
========================================================
Subsetting and asignment is typically done through bracket notation
```{r vectors3}
vec <- LETTERS[1:8] #notice the shortcut for sequential vectors
vec[c(2, 3, 4)] #can index with vectors
vec[-1] #negative values indicate removal
vec2 <- vec
vec2[5] <- "ZZZZZ" #can replace elements
vec2
```
Vectors
========================================================
Element-wise operations like addition, multiplication, etc. are easy using the normal +, *, etc. operators.
```{r vectors4}
vec1 <- 1:5
vec2 <- 2:6
print(vec1)
print(vec2)
vec1 + vec2
vec1 * vec2
```
Vectors
========================================================
Scalars can be applied to the entire vector
```{r vectors5}
vec <- 1:10
4 * vec
```
Vectors
========================================================
Make sure vectors are the same length or weird things can happen
```{r vectors6, warnings = TRUE}
1:2 + 1:10 #tries to do addition to subsets of the longer vector
```
Matrices and Arrays
========================================================
Matrices and arrays are multidimensional extensions of vectors that add a __dim__ attribute.
```{r matrix1}
mat <- matrix(1:9, nrow = 3, ncol = 3)
mat
arr <- array(1:12, dim = c(2, 3, 2))
arr
```
Matrices and Arrays
========================================================
Length will still work here and the __dim__ function is now defined.
```{r}
arr <- array(1:12, dim = c(2, 3, 2))
length(arr) #total # of elements
dim(arr)
```
Matrices and Arrays
========================================================
Subsetting is handled through square brackets with the use of commas to distinguish dimension
```{r matrix2}
mat <- matrix(1:12, nrow = 4, ncol = 3)
mat
mat[2:3, ] #leaving a column emtpy indicates all values of that dimension
mat[-1, 2] #one dimensional subsets will be reduced to vectors automatically
```
Matrices and Arrays
========================================================
Subsetting is handled through square brackets with the use of commas to distinguish dimension
```{r matrix3}
arrarr <- array(1:12, dim = c(2, 3, 2))
arr
arr[1, 1, 1] #single element
arr[1, 2:3, 1:2] #matrix
```
Matrices and Arrays
========================================================
Elementwise operations still work by default.
```{r matrix4}
mat1 <- matrix(1:9, nrow = 3, ncol = 3)
mat2 <- t(mat1) #transpose
mat1 + mat2
mat1 * mat2
```
Matrices and Arrays
========================================================
Make sure dimensions match up
```{r matrix5, eval = F}
mat1 <- matrix(1:9, nrow = 3, ncol = 3)
mat2 <- matrix(1:6, nrow = 2, ncol = 3)
mat1 + mat2 #will break
```
Matrices and Arrays
========================================================
Matrix multiplication is defined with the __%*%__ operator
```{r matrix6}
mat1 <- matrix(1:9, nrow = 3, ncol = 3)
mat2 <- matrix(1:6, nrow = 2, ncol = 3)
mat2 %*% mat1
```
Lists
========================================================
Lists are 1-dimensional collections of heterogenous objects.
```{r list1}
lis <- list(x = 1, y = LETTERS[1:5], z = matrix(1:9, 3, 3))
lis
```
Lists
========================================================
Lists can be subsetted multiple ways
```{r list2}
lis[[2]] #access element of the list
lis$y #access element of the list
lis["y"] #sub-list structure
```
Data Frames
========================================================
Data frames are a native 2-D tabular data object where each column can be a different type. These structures are the workhorses of much of R's data analysis ecosystem. They are very similar to pandas objects in Python.
Data Frames
========================================================
```{r}
x <- data.frame(A = 1:10, B = "hello",
C = seq.Date(from = Sys.Date(), length = 10, by = "day"))
x
```
Data Frames
========================================================
```{r}
summary(x)
```
Data Frames
========================================================
Data frames are typically subsetted like matrices or lists
```{r}
x[,1]
x$A
```
Data Frames
========================================================
Data frames are the standard structure for the __tidyverse__ ecosystem of packages which include
- dplyr
- tidyr
- ggplot2
- purrr
- ...
This is my prefered analysis pipeline and am giving a talk on it next!
Special Classes and Objects of Note
========================================================
As an object oriented programming language, you can define your own custom classes and data objects. Here are few special ones that show up a lot:
Factors
========================================================
Factors are character vectors with a fixed set of members/levels. This is particularly useful for categorical data.
```{r}
vec <- c("Denver", "Fort Collins", "Arvada", "Boulder")
factor(vec)
```
Factors
========================================================
Factors also have the ability to __ordered__. This allows you to map an ordering to non-numeric data.
```{r}
vec <- c("Denver", "Fort Collins", "Arvada", "Boulder")
factor(vec, ordered = T) #defaults to alphabetical
factor(vec, ordered = T, levels = c("Denver", "Boulder", "Arvada", "Fort Collins"))
```
Factors
========================================================
Just like with other classes, the __is__ and __as__ functions are useful here
```{r}
vec <- c("Denver", "Fort Collins", "Arvada", "Boulder")
factor_vec <- factor(vec, ordered = T) #defaults to alphabetical
factor_vec
as.character(factor_vec)
```
Factors
========================================================
Be very careful when coercing to numeric!
```{r}
vec <- c("1", "2", "100", "4")
factor_vec <- factor(vec) #defaults to alphabetical
factor_vec
as.numeric(factor_vec)
as.numeric(as.character(factor_vec))
```
Factors
========================================================
Factors become extremely useful when partitioning and manipulating larger data sets and visualizing groups. Check out the __forcats__ package for some better helper functions for factors
Date
========================================================
__Date__ is a built in class for handling year, month, and day information
```{r}
date <- Sys.Date()
class(date)
date
```
Date
========================================================
Really useful when you have multiple observations over time
```{r}
date <- Sys.Date()
date
date + 3 #adds 3 days
```
Date
========================================================
Really useful when you have multiple observations over time. Make sure to keep track of units!
```{r}
date1 <- Sys.Date()
date2 <- date1 + 3
date2 - date1
class(date2 - date1) #notice the difftime class
as.numeric(date2 - date1)
```
Date
========================================================
Can handle a lot of different date formats, etc.
```{r}
as.Date("2017-08-16")
as.Date("2017/08/16")
as.Date("August 16, 2017", format = "%B %d, %Y") #uses the strptime function to handle format
```
POSIX
========================================================
Date-time objects that extend Date to handle hour, minute, second information as well as timezones.
```{r}
Sys.time()
class(Sys.time())
#POSIXct represents seconds since Unix epoch + other stuff
#POSIXlt stores list of year, month, day, hour, minute, sec + other stuff
```
POSIX
========================================================
```{r}
as.POSIXct("2017-08-16")
as.POSIXct("2017-08-16") + 60 #Defaults to adding seconds
(as.POSIXct("2017-08-16") + 60) - (as.POSIXct("2017-08-16"))
```
POSIX
========================================================
Check out the __zoo__ and __lubridate__ packages for more advanced Date and POSIX functionality
Visualization
========================================================
Out of the box R is one of the easiest and most powerful visualization systems for data. Lots of standard visualizations are already implemented and only require a couple of lines. Customization and more advanced use cases can be handled through clever coding and flexible plotting options.
The plot() function
========================================================
class: small-code
```{r, eval = F,fig.width=12, fig.height=12, fig.show='hold', fig.align='center'}
x <- seq(0, 2*pi, by = 0.1)
y <- sin(x)
plot(x, y)
```
***
```{r, echo = F,fig.width=12, fig.height=12, fig.show='hold', fig.align='center'}
x <- seq(0, 2*pi, by = 0.1)
y <- sin(x)
plot(x, y)
```
The plot() function
========================================================
class: small-code
```{r, eval = F,fig.width=12, fig.height=12, fig.show='hold', fig.align='center'}
x <- seq(0, 2*pi, by = 0.1)
y <- sin(x)
plot(x, y, type = "l")
```
***
```{r, echo = F,fig.width=12, fig.height=12, fig.show='hold', fig.align='center'}
x <- seq(0, 2*pi, by = 0.1)
y <- sin(x)
plot(x, y, type = "l")
```
The plot() function
========================================================
class: small-code
```{r, eval = F,fig.width=12, fig.height=12, fig.show='hold', fig.align='center'}
x <- seq(0, 2*pi, by = 0.1)
y <- sin(x)
plot(x, y, type = "b", col = "dodgerblue", lty = 2, lwd = 3, pch = 20, cex = 2)
```
***
```{r, echo = F,fig.width=12, fig.height=12, fig.show='hold', fig.align='center'}
x <- seq(0, 2*pi, by = 0.1)
y <- sin(x)
plot(x, y, type = "b", col = "dodgerblue", lty = 2, lwd = 3, pch = 20, cex = 2)
```
The plot() function
========================================================
class: small-code
Can call an empty plot device and manually add elements
```{r, eval = F,fig.width=12, fig.height=12, fig.show='hold', fig.align='center'}
x <- seq(0, 2*pi, by = 0.1)
y <- sin(x)
noise <- jitter(y)
plot(x, y, type = "n", xlim = c(0, 1.5*pi))
lines(x, y, col = "maroon", lwd = 3)
points(x, noise, col = "pink", pch = 12)
title(main = "This is the title", xlab = "X Axis", ylab = "Y Axis",
cex.main = 2)
```
***
```{r, echo = F,fig.width=12, fig.height=12, fig.show='hold', fig.align='center'}
x <- seq(0, 2*pi, by = 0.1)
y <- sin(x)
noise <- y + rnorm(length(y), sd = .1)
plot(x, y, type = "n", xlim = c(0, 1.5*pi))
lines(x, y, col = "maroon", lwd = 3)
points(x, noise, col = "blue", pch = 17, cex = 3)
title(main = "This is the title", xlab = "X Axis", ylab = "Y Axis",
cex.main = 2, cex.lab = 2)
```
The hist() function
========================================================
class: small-code
Histograms are common ways to visualize distributions of data
```{r, eval = F,fig.width=12, fig.height=12, fig.show='hold', fig.align='center'}
x <- rnorm(1000) #random normal data
hist(x)
```
***
```{r, echo = F,fig.width=12, fig.height=12, fig.show='hold', fig.align='center'}
x <- rnorm(1000) #random normal data
hist(x)
```
The hist() function
========================================================
class: small-code
Can manipulate just like other plots
```{r, eval = F,fig.width=12, fig.height=12, fig.show='hold', fig.align='center'}
x <- rnorm(1000) #random normal data
title(main = "Histogram", sub = "Subtitle", xlab = "X Axis", ylab = "Y Axis")
```
***
```{r, echo = F,fig.width=12, fig.height=12, fig.show='hold', fig.align='center'}
x <- rnorm(1000) #random normal data
hist(x, col = "red", border = "blue")
title(main = "Histogram", sub = "Subtitle", xlab = "X Axis", ylab = "Y Axis")
```
Tons of other graphics built in
========================================================
- Bar charts
- Pie Charts
- Box plots
- Many advanced objects (regression models, time series, etc.) and objects have custom plotting methods defined for them that automatically produce one or more plots of interest
Data Import and Output
========================================================
R is __extremely__ flexible when it comes to importing data and it is constantly being extended. A few examples of methods that are included in base R or added through common packages.
- tabular data (csv, tsv, etc.)
- text files
- JSON
- database connections (SQL, Access, Mongo, pretty much anything you can think of)
- Web APIs (httr package really good here)
- "Big Data" frameworks (Hadoop, Spark, etc.)
In my practical experience, data import almost always boils down to tabular flat files like csvs. Databases are next most common. Obviously this depends on your use case.
Tabular Data Import
========================================================
__read.delim__ is the work horse base R function for reading in data. Both __read.csv__ and __read.tsv__ are special cases of this function.
```{r}
dat <- read.delim(file = "./2015_fuel_econ.csv", header = T, sep = ",")
class(dat)
head(dat)
```
Tabular Data Import
========================================================
__summary__ is a very useful function for dataframes
```{r}
dat <- read.delim(file = "./2015_fuel_econ.csv", header = T, sep = ",")
summary(dat)
```
Tabular Data Import
========================================================
__glimpse__ is a useful alternative for quick inspection
```{r}
dat <- read.delim(file = "./2015_fuel_econ.csv", header = T, sep = ",")
dplyr::glimpse(dat)
```
Output
========================================================
For every input data format there typically is an equivalent output format. The __write__ functions for tabular data are the most common functions here.
```{r, eval = F}
x <- matrix(1:9, 3, 3)
x_df <- as.data.frame(x)
write.csv(x, file = "x.csv") #takes either matrix or array
write.csv(x_df, file = "x_df.csv")
```
RData Objects
========================================================
You can save multiple objects as a single RData object using the __save__ function. When you load these objects back into R, they will be the same as before. No extraction required
```{r}
x <- matrix(1:9, 3, 3)
y <- LETTERS[1:9]
z <- "pineapple"
save(x, y, z, file = "test_objects.RData")
rm(list = ls()) #clears my workspace
load("test_objects.RData") #Everything is back to normal
x
```
RData Objects
========================================================
The concept of "saving your workspace" does this for everything in memory at the time of saving.
Statistics
========================================================
How have we gotten this far into an R talk without talking about a ton of statistics!? The built in data structures and visualization capabilities of R make it the go to for the current generation of statistical research (not to mention that it is free). Here are a few things it is good at out of the box or with common packages:
- Simple statistical models (linear regression, ANOVA, logistic regression, etc.)
- Generating random data according to distributions (Normal, Exponential, Poisson, etc.)
- Statistical tests (t-tests, Chi Squared, etc.)
- Tons more...
Rather than give a lecture on statistics, I thought I would do a few demos of using all of R's functionality to answer some statistical questions about data. (See the attached scripts)