-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession3.Rmd
584 lines (385 loc) · 12.4 KB
/
session3.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
---
title: "Creating and manipulating objects, and extending R using packages"
subtitle: "Learning the basics of R - Part 2"
author:
- "Ernest Guevarra"
date: '25 October 2024'
output:
xaringan::moon_reader:
css: xaringan-themer.css
nature:
slideNumberFormat: "%current%"
highlightStyle: github
highlightLines: true
ratio: 16:9
countIncrementalSlides: true
---
```{r setup, include=FALSE}
options(htmltools.dir.version = FALSE)
knitr::opts_chunk$set(
fig.width=9, fig.height=3.5, fig.retina=3,
out.width = "100%",
cache = FALSE,
echo = TRUE,
message = FALSE,
warning = FALSE,
hiline = TRUE
)
if (!require(remotes)) install.packages("remotes")
if (!require(fontawesome)) remotes::install_github("rstudio/fontawesome")
```
```{r xaringan-themer, include=FALSE, warning=FALSE}
library(xaringanthemer)
style_mono_light(
base_color = "#002147",
title_slide_background_image = "",
title_slide_background_size = "cover",
header_font_google = google_font("Fira Sans"),
text_font_google = google_font("Fira Sans Condensed"),
text_font_size = "1.2em",
link_color = "#214700",
header_h1_font_size = "50px",
header_h2_font_size = "40px",
header_h3_font_size = "30px",
code_font_google = google_font("Fira Mono"),
text_slide_number_font_size = "0.5em",
footnote_font_size = "0.5em"
)
```
# Outline
1. Base functions in R
* What is a function?
* Basic function syntax
2. Extending R using packages
* What are packages?
* How to install packages
* Loading packages to the environment
3. Accessing and reading data into R
---
# What is a function?
* A set of statements organized together to perform a specific task.
* R has a large number of in-built functions.
* In R, a function is an object so the R interpreter is able to pass control to the function, along with arguments that may be necessary for the function to accomplish the actions.
* The function in turn performs its task and returns control to the interpreter as well as any result which may be stored in other objects.
---
# Functions in R
## Base functions
* Term we use for built-in functions in R.
* These functions cover a wide range of purposes, use cases, and applications one of which is for statistical analysis (probably the most common built-in functions in R)
* Everything we do in R is almost always mediated/made possible by using functions
## Basic function syntax
```{r, echo = TRUE, eval = FALSE}
function_name(argument1, argument2, ...)
```
---
# Using functions - accessing R builtin dataset
.pull-left[
* First let us use some sample/toy data. R has built-in datasets for teaching/testing purposes. We will continue on the BMI theme from yesterday by accessing the `women` built-in dataset in R. This dataset is of average height (inches) and weight (lbs) of women age 30-39 years old.
* We access this data using the `data()` function as follows:
```{r, echo = TRUE}
data("women")
```
]
.pull-right[
```{r, echo = TRUE}
women
```
]
---
# Using functions - exploring data structure
* Being able to understand the **data structure** of a dataset helps us make good decisions on how to work with data or how to analyse data.
* There are several R functions that gives us the characteristics and structure of a dataset such as:
* The shape of the data
* The number of records in the data
* The variables of the data
* The number of variables in the data
* The values of variables in the data
---
# Using functions - describing the shape of the data
* We use the `class()` function to know the **class** attribute of an R object.
* Knowing the **class** of an R object give us information on what kind of object it is and how we can work with it in R
## Task:
* Using the `women` dataset that we just loaded, apply the `class()` function:
--
```{r, echo = TRUE}
## Get class of women dataset
class(women)
```
---
# Using functions - number of records in the data
* We often need to know how many records are in the dataset that we are working on.
* This is useful for various statistical analysis that we perform on data.
* The function `nrow()` gives us the number of rows of a `data.frame` R object
## Task:
* Using the `women` dataset, apply the `nrow()` function to get the number of rows:
--
```{r, echo = TRUE}
## Get number of rows of women dataset
nrow(women)
```
---
# Using functions - number of records in the data
## Bonus question:
* How many columns does the `women` dataset have?
--
```{r, echo = TRUE}
ncol(women)
```
---
# Using functions - variable names of a dataset
* We often need to know the variables of the dataset that we are working on.
* This is useful for various statistical analysis that we perform on data.
* The function `names()` gives us the variable names of a `data.frame` R object
## Task:
* Using the `women` dataset, apply the `names()` function to get the variable names:
--
```{r, echo = TRUE}
## Get variable names of women dataset
names(women)
```
---
# Using functions - variable names of a dataset
## Bonus questions:
* Can you describe the shape and structure of the output of `names(women)`?
--
```{r, echo = TRUE}
## Get class of variable names of women dataset
class(names(women))
```
--
* Can you get how *LONG* (how many variable names) the output of `names(women)` is?
--
```{r, echo = TRUE}
## Get length of the variable names of women dataset
length(names(women))
```
---
# Using functions - describing the structure of a dataset
* Another approach to get a full description of the structure of a dataset object in R is by using the `str` function
```{r, echo = TRUE}
str(women)
```
--
* The output of using `str()` function is comprehensive.
* It gives us the class of the object
* It gives us the number of records/observations
* It gives us the number of variables
* It gives us the names of the variables
* It gives us the class of each of the variables
* It gives us a glimpse of the values of each of the variables
---
# Using functions - accessing the variables of a dataset
* When working with `data.frame` objects, we often need to use/access only a specific variable in that `data.frame` object
* Knowing how to access a specific variable in a `data.frame` object is one of the most important skill in R
* There are several ways to access a specific variable in a `data.frame` object
---
# Using functions - accessing the variables of a dataset
## Using the `$` operator
* Access the **`height`** variable using the **`$`** operator
```{r, echo = TRUE}
women$height
```
--
* Now try to access the **`weight`** variable using the **`$`** operator
--
```{r, echo = TRUE}
women$weight
```
---
# Using functions - accessing the variables of a dataset
## Using the indexing method - `[ ]`
* Access the **`height`** variable using **`[ ]`**
```{r, echo = TRUE}
women[ , "height"]
women[ , 1]
women[[1]]
```
---
# Using functions - accessing the variables of a dataset
## Using the indexing method - `[ ]`
* Now try to access the **`weight`** variable using **`[ ]`**
--
```{r, echo = TRUE}
women[ , "weight"]
women[ , 2]
women[[2]]
```
---
# Using functions - accessing other values of a dataset
## Bonus question:
* Access the **`height`** value for the **third** row/record of the dataset
--
```{r, echo = TRUE}
women[3, "height"]
```
--
```{r, echo = TRUE}
women[ , "height"][3]
```
---
# Using functions - accessing other values of a dataset
## Bonus question:
* Access the **`height`** value for the **third** row/record of the dataset
```{r, echo = TRUE}
women[3, ]["height"]
```
--
```{r, echo = TRUE}
women[3, ][["height"]]
```
--
```{r, echo = TRUE}
women$height[3]
```
---
# Using functions - some basic statistical functions
```{r, echo = FALSE}
function_name <- c("mean()", "median()", "var()", "sd()", "scale()")
function_description <- c(
"Get the mean value of a set of numbers",
"Get the median value of a set of numbers",
"Get the estimated variance of the population from which you sampled",
"Get the standard deviation of the population from which you sampled",
"Get the z-scores for a set of numbers"
)
data.frame(function_name, function_description) |>
knitr::kable(
row.names = FALSE,
col.names = c("Function", "Description")
) |>
kableExtra::kable_styling(
bootstrap_options = "striped",
full_width = FALSE,
position = "center"
)
```
---
# Using functions - application of some basic statistical functions
## 1. Get the mean height in the `women` dataset
## 2. Get the median weight in the `women` dataset
--
```{r, echo = TRUE}
mean(women$height)
```
```{r, echo = TRUE}
median(women$weight)
```
---
# Extending R using packages
* There are times that we need functions that are not built-in to R but are available through external **R packages**
* **R packages** are collections of functions and data sets developed by the community.
* **R packages** increase the power of R by improving existing base R functionalities, or by adding new ones.
* For this project, majority of the statistical tools/functions we need are already built-in to R.
* However, most of the tools we need for data access and loading, data manipulation, data processing, creating reports, reproducibility, and automation will require us to extend R using these additional **R packages**
---
# Extending R using packages
* We usually have our data in different files and these files can be in different file formats.
* Depending on the file format of your data, different functions are used to read these files into R.
* Base (built-in) functions in R have a limited types of data that it can read.
* We often need to install additional **R packages** to read other types of data e.g., `.XLSX`, `.dta`, `.sav`, etc.
---
# Extending R using packages
* Using `read.table()` base function in R to read a `text` type of data file such as a *comma-separated value* or `CSV` file:
.pull-left[
```{r, echo = TRUE, eval = FALSE}
read.table(
file = "data/women.csv",
header = TRUE, sep = ","
)
```
]
.pull-right[
```{r, echo = FALSE, eval = TRUE}
read.table(
file = "data/women.csv",
header = TRUE, sep = ","
)
```
]
---
# Extending R using packages
* Using `read.csv()` base function in R to read a `text` type of data file such as a *comma-separated value* or `CSV` file:
.pull-left[
```{r, echo = TRUE, eval = FALSE}
read.csv(file = "data/women.csv")
```
]
.pull-right[
```{r, echo = FALSE, eval = TRUE}
read.csv(file = "data/women.csv")
```
]
---
# Extending R using packages
* We should assign this data to an object. Let us call this object `women_csv`
.pull-left[
```{r, echo = TRUE, eval = TRUE}
women_csv <- read.csv("data/women.csv")
```
]
.pull-right[
```{r, echo = FALSE, eval = TRUE}
women_csv
```
]
---
# Extending R using packages
* Using the R package `openxlsx` to read a Microsoft Excel or `.XLSX` type of data file
* We first need to install the `openxlsx` package
```{r, echo = TRUE, eval = FALSE}
install.packages("openxlsx")
```
--
* We then need to load the package into the current working environment. We use the `library()` function for this:
```{r, echo = TRUE}
library("openxlsx")
```
---
# Extending R using packages
* Using the R package `openxlsx` to read a Microsoft Exel or `.XLSX` type of data file
* We are now ready to use the function `read.xlsx()` from the `openxlsx` package to read the `women.xlsx` file:
.pull-left[
```{r, echo = TRUE, eval = FALSE}
read.xlsx(
xlsxFile = "data/women.xlsx",
sheet = 1
)
```
]
.pull-right[
```{r, echo = FALSE, eval = TRUE}
read.xlsx(
xlsxFile = "data/women.xlsx",
sheet = 1
)
```
]
---
# Extending R using packages
* We should assign this data to an object. Let us call this object `women_xlsx`
.pull-left[
```{r, echo = TRUE, eval = TRUE}
women_xlsx <- read.xlsx(
xlsxFile = "data/women.xlsx",
sheet = 1
)
```
]
.pull-right[
```{r, echo = TRUE}
women_xlsx
```
]
---
class: inverse, center, middle
# Coding challenge
Check your email and look for the message from GitHub Classroom with a link to your next coding exercise.
---
class: inverse, center, middle
# Questions?
---
class: inverse, center, middle
# Thank you!
Slides can be viewed at https://oxford-ihtm.io/open-reproducible-science/session3.html
PDF version of slides can be downloaded at https://oxford-ihtm.io/open-reproducible-science/pdf/session3-r-basics-part2.pdf
R scripts for slides available [here](https://github.com/OxfordIHTM/open-reproducible-science/blob/main/session3.Rmd)