-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_r_intro.qmd
More file actions
264 lines (182 loc) · 6.3 KB
/
01_r_intro.qmd
File metadata and controls
264 lines (182 loc) · 6.3 KB
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
# Intro to R
In Quarto documents like this one, we can write comments by just using plain text. In contrast, code needs to be within *code blocks*, like the one below. To execute a code block, you can click on the little "Play" button or press `Cmd/Ctrl + Shift + Enter` when your keyboard is hovering the code block.
```{r}
2 + 2
```
That was our first R command, a simple math operation. Of course, we can also do more complex arithmetic:
```{r}
12345 ^ 2 / (200 + 25 - 6 * 2) # this is an inline comment, see the leading "#"
```
In order to *create* a code block, you can press `Cmd/Ctrl + Alt + i` or click on the little green "+C" icon on top of the script.
::: callout-note
#### Exercise
Create your own code block below and run a math operation.
:::
## Objects
A huge part of R is working with *objects*. Let's see how they work:
```{r}
my_object <- 10 # opt/alt + minus sign will make the arrow
```
```{r}
my_object # to print the value of an object, just call its name
```
We can now use this object in our operations:
```{r}
2 ^ my_object
```
Or even create another object out of it:
```{r}
my_object2 <- my_object * 2
```
```{r}
my_object2
```
You can delete objects with the `rm()` function (for "remove"):
```{r}
rm(my_object2)
```
## Vectors and functions
Objects can be of different types. One of the most useful ones is the *vector*, which holds a series of values. To create one manually, we can use the `c()` function (for "combine"):
```{r}
my_vector <- c(6, -11, my_object, 0, 20)
```
```{r}
my_vector
```
One can also define vectors by sequences:
```{r}
3:10
```
We can use square brackets to retrieve parts of vectors:
```{r}
my_vector[4] # fourth element
```
```{r}
my_vector[1:2] # first two elements
```
Let's check out some basic functions we can use with numbers and numeric vectors:
```{r}
sqrt(my_object) # squared root
```
```{r}
log(my_object) # logarithm (natural by default)
```
```{r}
abs(-5) # absolute value
```
```{r}
mean(my_vector)
```
```{r}
median(my_vector)
```
```{r}
sd(my_vector) # standard deviation
```
```{r}
sum(my_vector)
```
```{r}
min(my_vector) # minimum value
```
```{r}
max(my_vector) # maximum value
```
```{r}
length(my_vector) # length (number of elements)
```
Notice that if we wanted to save any of these results for later, we would need to *assign* them:
```{r}
my_mean <- mean(my_vector)
```
```{r}
my_mean
```
These functions are quite simple: they take one object and do one operation. A lot of functions are a bit more complex---they take multiple objects or take options. For example, see the `sort()` function, which by default sorts a vector *increasingly*:
```{r}
sort(my_vector)
```
If we instead want to sort our vector *decreasingly*, we can use the `decreasing = TRUE` argument (`T` also works as an abbreviation for `TRUE`).
```{r}
sort(my_vector, decreasing = TRUE)
```
::: callout-tip
If you use the argument values in order, you can avoid writing the argument names (see below). This is sometimes useful, but can also lead to confusing code---use it with caution.
```{r}
sort(my_vector, T)
```
:::
A useful function to create vectors in sequence is `seq()`. Notice its arguments:
```{r}
seq(from = 30, to = 100, by = 5)
```
To check the arguments of a function, you can examine its help file: look the function up on the "Help" panel on RStudio or use a command like the following: `?sort`.
::: callout-note
#### Exercise
Examine the help file of the `log()` function. How can we compute the the base-10 logarithm of `my_object`? Your code:
:::
Other than numeric vectors, character vectors are also useful:
```{r}
my_character_vector <- c("Apple", "Orange", "Watermelon", "Banana")
```
```{r}
my_character_vector[3]
```
```{r}
nchar(my_character_vector) # count number of characters
```
## Data frames and lists
Another useful object type is the *data frame*. Data frames can store multiple vectors in a tabular format. We can manually create one with the `data.frame()` function:
```{r}
my_data_frame <- data.frame(fruit = my_character_vector,
calories_per_100g = c(52, 47, 30, 89),
water_per_100g = c(85.6, 86.8, 91.4, 74.9))
```
```{r}
my_data_frame
```
Now we have a little 4x3 data frame of fruits with their calorie counts and water composition. We gathered the nutritional information from the [USDA (2019)](https://fdc.nal.usda.gov/).
We can use the `data_frame$column` construct to access the vectors within the data frame:
```{r}
mean(my_data_frame$calories_per_100g)
```
::: callout-note
#### Exercise
Obtain the maximum value of water content per 100g in the data. Your code:
:::
Some useful commands to learn attributes of our data frame:
```{r}
dim(my_data_frame)
```
```{r}
nrow(my_data_frame)
```
```{r}
names(my_data_frame) # column names
```
We will learn much more about data frames in our next module on data analysis.
After talking about vectors and data frames, the last object type that we will cover is the *list*. Lists are super flexible objects that can contain just about anything:
```{r}
my_list <- list(my_object, my_vector, my_data_frame)
```
```{r}
my_list
```
To retrieve the elements of a list, we need to use double square brackets:
```{r}
my_list[[1]]
```
Lists are sometimes useful due to their flexibility, but are much less common in routine data analysis compared to vectors or data frames.
## Packages
The R community has developed thousands of *packages*, which are specialized collections of functions, datasets, and other resources. To install one, you should use the `install.packages()` command. Below we will install the `tidyverse` package, a suite for data analysis that we will use in the next modules. You just need to install packages once, and then they will be available system-wide.
```{r}
#| eval: false
install.packages("tidyverse") # this can take a couple of minutes
```
If you want to use an installed package in your script, you must load it with the `library()` function. Some packages, as shown below, will print descriptive messages once loaded.
```{r}
library(tidyverse)
```
::: callout-warning
Remember that `install.packages("package")` needs to be executed just once, while `library(package)` needs to be in each script in which you plan to use the package. In general, never include `install.packages("package")` as part of your scripts or Quarto documents!
:::