forked from datacarpentry/R-ecology-lesson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01-intro-to-R.Rmd
273 lines (205 loc) · 8.42 KB
/
01-intro-to-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
---
title: "Introduction to R"
author: "Data Carpentry contributors"
minutes: 45
output: pdf_document
layout: topic
---
```{r, echo=FALSE, purl=FALSE, message = FALSE}
source("setup.R")
```
------------
> ## Learning Objectives
>
> * Familiarize participants with R syntax
> * Understand the concepts of objects and assignment
> * Understand the concepts of vector and data types
> * Get exposed to a few functions
------------
## The R syntax
_Start by showing an example of a script_
* Point to the different parts:
- a function
- the assignment operator `<-`
- the `=` for arguments
- the comments `#` and how they are used to document function and its content
- the `$` operator
* Point to indentation and consistency in spacing to improve clarity
![Example of a simple R script](img/r_starting_example_script.png)
## Creating objects
```{r, echo=FALSE, purl=TRUE}
### Creating objects in R
```
You can get output from R simply by typing in math in the console
```{r, purl=FALSE}
3 + 5
12/7
```
However, to do useful and interesting things, we need to assign _values_ to
_objects_. To create an object, we need to give it a name followed by the
assignment operator `<-`, and the value we want to give it:
```{r, purl=FALSE}
weight_kg <- 55
```
Objects can be given any name such as `x`, `current_temperature`, or
`subject_id`. You want your object names to be explicit and not too long. They
cannot start with a number (`2x` is not valid, but `x2` is). R is case sensitive
(e.g., `weight_kg` is different from `Weight_kg`). There are some names that
cannot be used because they are the names of fundamental functions in R (e.g.,
`if`, `else`, `for`, see
[here](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Reserved.html)
for a complete list). In general, even if it's allowed, it's best to not use
other function names (e.g., `c`, `T`, `mean`, `data`, `df`, `weights`). In doubt
check the help to see if the name is already in use. It's also best to avoid
dots (`.`) within a variable name as in `my.dataset`. There are many functions
in R with dots in their names for historical reasons, but because dots have a
special meaning in R (for methods) and other programming languages, it's best to
avoid them. It is also recommended to use nouns for variable names, and verbs
for function names. It's important to be consistent in the styling of your code
(where you put spaces, how you name variable, etc.). In R, two popular style
guides are [Hadley Wickham's](http://adv-r.had.co.nz/Style.html) and
[Google's](https://google-styleguide.googlecode.com/svn/trunk/Rguide.xml).
When assigning a value to an object, R does not print anything. You can force to
print the value by using parentheses or by typing the name:
```{r, purl=FALSE}
weight_kg <- 55 # doesn't print anything
(weight_kg <- 55) # but putting parenthesis around the call prints the value of `weight_kg`
weight_kg # and so does typing the name of the object
```
Now that R has `weight_kg` in memory, we can do arithmetic with it. For
instance, we may want to convert this weight in pounds (weight in pounds is 2.2
times the weight in kg):
```{r, purl=FALSE}
2.2 * weight_kg
```
We can also change a variable's value by assigning it a new one:
```{r, purl=FALSE}
weight_kg <- 57.5
2.2 * weight_kg
```
This means that assigning a value to one variable does not change the values of
other variables. For example, let's store the animal's weight in pounds in a new
variable, `weight_lb`:
```{r, purl=FALSE}
weight_lb <- 2.2 * weight_kg
```
and then change `weight_kg` to 100.
```{r, purl=FALSE}
weight_kg <- 100
```
What do you think is the current content of the object `weight_lb`? 126.5 or 200?
### Challenge
What are the values after each statement in the following?
```{r, purl=FALSE}
mass <- 47.5 # mass?
age <- 122 # age?
mass <- mass * 2.0 # mass?
age <- age - 20 # age?
mass_index <- mass/age # mass_index?
```
## Vectors and data types
```{r, echo=FALSE, purl=TRUE}
### Vectors and data types
```
A vector is the most common and basic data structure in R, and is pretty much
the workhorse of R. It's a group of values, mainly either numbers or
characters. You can assign this list of values to a variable, just like you
would for one item. For example we can create a vector of animal weights:
```{r, purl=FALSE}
weights <- c(50, 60, 65, 82)
weights
```
A vector can also contain characters:
```{r, purl=FALSE}
animals <- c("mouse", "rat", "dog")
animals
```
There are many functions that allow you to inspect the content of a
vector. `length()` tells you how many elements are in a particular vector:
```{r, purl=FALSE}
length(weights)
length(animals)
```
An important feature of a vector, is that all of the elements are the same type of data.
The function `class()` indicates the class (the type of element) of an object:
```{r, purl=FALSE}
class(weights)
class(animals)
```
The function `str()` provides an overview of the object and the elements it
contains. It is a really useful function when working with large and complex
objects:
```{r, purl=FALSE}
str(weights)
str(animals)
```
You can add elements to your vector by using the `c()` function:
```{r, purl=FALSE}
weights <- c(weights, 90) # adding at the end of the vector
weights <- c(30, weights) # adding at the beginning of the vector
weights
```
What happens here is that we take the original vector `weights`, and we are
adding another item first to the end of the other ones, and then another item at
the beginning. We can do this over and over again to grow a vector, or assemble
a dataset. As we program, this may be useful to add results that we are
collecting or calculating.
We just saw 2 of the 6 **atomic vector** types that R uses: `"character"` and
`"numeric"`. These are the basic building blocks that all R objects are built
from. The other 4 are:
* `"logical"` for `TRUE` and `FALSE` (the boolean data type)
* `"integer"` for integer numbers (e.g., `2L`, the `L` indicates to R that it's an integer)
* `"complex"` to represent complex numbers with real and imaginary parts (e.g.,
`1+4i`) and that's all we're going to say about them
* `"raw"` that we won't discuss further
Vectors are one of the many **data structures** that R uses. Other important
ones are lists (`list`), matrices (`matrix`), data frames (`data.frame`) and
factors (`factor`).
### Challenge
* **Question**: We’ve seen that atomic vectors can be of type character,
numeric, integer, and logical. But what happens if we try to mix these types in
a single vector?
* _Answer_: R implicitly converts them to all be the same type
* **Question**: Why do you think it happens?
* _Answer_: Vectors can be of only one data type. R tries to convert (=coerce)
the content of this vector to find a "common denominator".
* **Question**: Can you draw a diagram that represents the hierarchy of the data
types?
* _Answer_: `logical --> numeric --> character <-- logical`
```{r, echo=TRUE, eval=FALSE, purl=TRUE}
## We’ve seen that atomic vectors can be of type character, numeric, integer, and
## logical. But what happens if we try to mix these types in a single
## vector?
## What will happen in each of these examples? (hint: use `class()` to
## check the data type of your object)
num_char <- c(1, 2, 3, 'a')
num_logical <- c(1, 2, 3, TRUE)
char_logical <- c('a', 'b', 'c', TRUE)
tricky <- c(1, 2, 3, '4')
## Why do you think it happens?
## Can you draw a diagram that represents the hierarchy of the data
## types?
```
## Missing data
As R was designed to work with data, it includes the concept of missing data
(which is uncommon in other programming languages). Missing data are represented
as `NA`.
```{r, purl=FALSE}
planets <- c("Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus",
"Neptune", NA)
```
When doing operations on numbers, most functions will return `NA` if the data
you are working with include missing values. It is a safer behavior as otherwise
you may overlook that you are dealing with missing data. You can add the
argument `na.rm=TRUE` to calculate the result while ignoring the missing values.
```{r, purl=FALSE}
heights <- c(2, 4, 4, NA, 6)
mean(heights)
max(heights)
mean(heights, na.rm = TRUE)
max(heights, na.rm = TRUE)
```
If your data include missing values, you may want to become familiar with the
functions `is.na()`, `na.omit()`, and `complete.cases()`.
Next, we will use the "surveys" dataset to explore the `data.frame` data
structure, which is one of the most common types of R objects.