forked from datacarpentry/R-ecology-lesson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-starting-with-data.Rmd
715 lines (582 loc) · 27 KB
/
02-starting-with-data.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
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
---
title: "Starting with data"
author: "Data Carpentry contributors"
minutes: 20
---
```{r, echo=FALSE, purl=FALSE, message = FALSE}
source("setup.R")
```
------------
> ### Learning Objectives
>
> * Load external data from a .csv file into a data frame.
> * Describe what a data frame is.
> * Summarize the contents of a data frame.
> * Use indexing to subset specific portions of data frames.
> * Describe what a factor is.
> * Convert between strings and factors.
> * Reorder and rename factors.
> * Change how character strings are handled in a data frame.
> * Format dates.
------------
## Loading the survey data
```{r, echo=FALSE, purl=TRUE}
### Loading the survey data
```
We are investigating the animal species diversity and weights found within plots
at our study site. The dataset is stored as a comma separated value (CSV) file.
Each row holds information for a single animal, and the columns represent:
| Column | Description |
|------------------|------------------------------------|
| record\_id | Unique id for the observation |
| month | month of observation |
| day | day of observation |
| year | year of observation |
| plot\_id | ID of a particular plot |
| species\_id | 2-letter code |
| sex | sex of animal ("M", "F") |
| hindfoot\_length | length of the hindfoot in mm |
| weight | weight of the animal in grams |
| genus | genus of animal |
| species | species of animal |
| taxon | e.g. Rodent, Reptile, Bird, Rabbit |
| plot\_type | type of plot |
### Downloading the data
We are going to use the R function `download.file()` to download the CSV file
that contains the survey data from Figshare, and we will use `read_csv()` to
load the content of the CSV file into R.
Inside the `download.file` command, the first entry is a character string with the
source URL ("https://ndownloader.figshare.com/files/2292169").
This source URL downloads a CSV file from figshare. The text after the comma
("data_raw/portal_data_joined.csv") is the destination of the file on your local
machine. You'll need to have a folder on your machine called "data_raw" where
you'll download the file. So this command downloads a file from Figshare, names
it "portal_data_joined.csv" and adds it to a preexisting folder named "data_raw".
```{r, eval=FALSE, purl=TRUE}
download.file(url = "https://ndownloader.figshare.com/files/2292169",
destfile = "data_raw/portal_data_joined.csv")
```
### Reading the data into R
The file has now been downloaded to the destination you specified, but R has not
yet loaded the data from the file into memory. To do this, we can use the
`read_csv()` function from the **`tidyverse`** package.
Packages in R are basically sets of additional functions that let you do more
stuff. The functions we've been using so far, like `round()`, `sqrt()`, or `c()`,
come built into R; packages give you access to additional functions.
Before you use a package for the first time you need to install it on your
machine, and then you should import it in every subsequent R session when you
need it.
To install the **`tidyverse`** package, we can type
`install.packages("tidyverse")` straight into the console. In fact, it's better
to write this in the console than in our script for any package, as there's no
need to re-install packages every time we run the script.
Then, to load the package type:
```{r, message = FALSE, purl = FALSE}
## load the tidyverse packages, incl. dplyr
library(tidyverse)
```
Now we can use the functions from the **`tidyverse`** package.
Let's use `read_csv()` to read the data into a data frame
(we will learn more about data frames later):
```{r, eval=TRUE, purl=FALSE}
surveys <- read_csv("data_raw/portal_data_joined.csv")
```
You will see the message `Parsed with column specification`, followed by each
column name and its data type.
When you execute `read_csv` on a data file, it looks through the first 1000 rows
of each column and guesses its data type. For example, in this dataset,
`read_csv()` reads `weight` as `col_double` (a numeric data type), and `species`
as `col_character`. You have the option to specify the data type for a column
manually by using the `col_types` argument in `read_csv`.
We can see the contents of the first few lines of the data by typing its
name: `surveys`. By default, this will show show you as many rows and columns of
the data as fit on your screen.
If you wanted to the first 50 rows, you could type `print(surveys, n = 50)`
We can also extract the first few lines of this data using the function
`head()`:
```{r, results='show', purl=FALSE}
head(surveys)
```
Unlike the `print()` function, `head()` returns the extracted data. You could
use it to assign the first 100 rows of `surveys` to an object using
`surveys_sample <- head(surveys, 100)`. This can be useful if you want to try
out complex computations on a subset of your data before you apply them to the
whole data set.
There is a similar function that lets you extract the last few lines of the data
set. It is called (you might have guessed it) `tail()`.
To open the dataset in RStudio's Data Viewer, use the `view()` function:
```{r, eval = FALSE, purl = FALSE}
view(surveys)
```
> ### Note
>
> `read_csv()` assumes that fields are delineated by commas, however, in several
> countries, the comma is used as a decimal separator and the semicolon (;) is
> used as a field delineator. If you want to read in this type of files in R,
> you can use the `read_csv2()` function. It behaves like `read_csv()` but
> uses different parameters for the decimal and the field separators.
There is also the `read_tsv()` for tab separated data files and `read_delim()`
> for less common formats.
> Check out the help for `read_csv()` by typing `?read_csv` to learn more.
>
> In addition to the above versions of the csv format, you should develop the habits
> of looking at and record some parameters of your csv files. For instance,
> the character encoding, control characters used for line ending, date format
> (if the date is not splitted into three variables), and the presence of unexpected
> [newlines](https://en.wikipedia.org/wiki/Newline) are important characteristics of your data files.
> Those parameters will ease up the import step of your data in R.
## What are data frames?
When we loaded the data into R, it got stored as an object of class `tibble`,
which is a special kind of data frame (the difference is not important for our
purposes, but you can learn more about tibbles
[here](https://tibble.tidyverse.org/)).
Data frames are the _de facto_ data structure for most tabular data, and what we
use for statistics and plotting.
Data frames can be created by hand, but most commonly they are generated by
functions like `read_csv()`; in other words, when importing
spreadsheets from your hard drive or the web.
A data frame is the representation of data in the format of a table where the
columns are vectors that all have the same length. Because columns are
vectors, each column must contain a single type of data (e.g., characters, integers,
factors). For example, here is a figure depicting a data frame comprising a
numeric, a character, and a logical vector.
![](./img/data-frame.svg)
We can see this also when inspecting the <b>str</b>ucture of a data frame
with the function `str()`:
```{r, purl=FALSE}
str(surveys)
```
## Inspecting data frames
We already saw how the functions `head()` and `str()` can be useful to check the
content and the structure of a data frame. Here is a non-exhaustive list of
functions to get a sense of the content/structure of the data. Let's try them out!
* Size:
* `dim(surveys)` - returns a vector with the number of rows in the first element,
and the number of columns as the second element (the **dim**ensions of
the object)
* `nrow(surveys)` - returns the number of rows
* `ncol(surveys)` - returns the number of columns
* Content:
* `head(surveys)` - shows the first 6 rows
* `tail(surveys)` - shows the last 6 rows
* Names:
* `names(surveys)` - returns the column names (synonym of `colnames()` for `data.frame`
objects)
* `rownames(surveys)` - returns the row names
* Summary:
* `str(surveys)` - structure of the object and information about the class, length and
content of each column
* `summary(surveys)` - summary statistics for each column
Note: most of these functions are "generic", they can be used on other types of
objects besides `data.frame`.
> ### Challenge
>
> Based on the output of `str(surveys)`, can you answer the following questions?
>
> * What is the class of the object `surveys`?
> * How many rows and how many columns are in this object?
>
> ```{r, answer=TRUE, results="markup", purl=FALSE}
>
> str(surveys)
>
> ## * class: data frame
> ## * how many rows: 34786, how many columns: 13
>
> ```
```{r, echo=FALSE, purl=TRUE}
## Challenge
## Based on the output of `str(surveys)`, can you answer the following questions?
##
## * What is the class of the object `surveys`?
## * How many rows and how many columns are in this object?
```
## Indexing and subsetting data frames
```{r, echo=FALSE, purl=TRUE}
## Indexing and subsetting data frames
```
Our survey data frame has rows and columns (it has 2 dimensions), if we want to
extract some specific data from it, we need to specify the "coordinates" we
want from it. Row numbers come first, followed by column numbers. However, note
that different ways of specifying these coordinates lead to results with
different classes.
```{r, purl=FALSE}
# first element in the first column of the data frame (as a vector)
surveys[1, 1]
# first element in the 6th column (as a vector)
surveys[1, 6]
# first column of the data frame (as a vector)
surveys[, 1]
# first column of the data frame (as a data.frame)
surveys[1]
# first three rows of the 6th column (as a vector)
surveys[1:3, 6]
# the 3rd row of the data frame (as a data.frame)
surveys[3, ]
# equivalent to head_surveys <- head(surveys)
head_surveys <- surveys[1:6, ]
```
`:` is a special function that creates numeric vectors of integers in increasing
or decreasing order, test `1:10` and `10:1` for instance.
You can also exclude certain indices of a data frame using the "`-`" sign:
```{r, purl=FALSE}
surveys[, -1] # The whole data frame, except the first column
surveys[-(7:34786), ] # Equivalent to head(surveys)
```
Data frames can be subset by calling indices (as shown previously), but also by calling their column names directly:
```{r, eval = FALSE, purl=FALSE}
surveys["species_id"] # Result is a data.frame
surveys[, "species_id"] # Result is a vector
surveys[["species_id"]] # Result is a vector
surveys$species_id # Result is a vector
```
In RStudio, you can use the autocompletion feature to get the full and correct names of the columns.
> ### Challenge
>
> 1. Create a `data.frame` (`surveys_200`) containing only the data in
> row 200 of the `surveys` dataset.
>
> 2. Notice how `nrow()` gave you the number of rows in a `data.frame`?
>
> * Use that number to pull out just that last row in the data frame.
> * Compare that with what you see as the last row using `tail()` to make
> sure it's meeting expectations.
> * Pull out that last row using `nrow()` instead of the row number.
> * Create a new data frame (`surveys_last`) from that last row.
>
> 3. Use `nrow()` to extract the row that is in the middle of the data
> frame. Store the content of this row in an object named `surveys_middle`.
>
> 4. Combine `nrow()` with the `-` notation above to reproduce the behavior of
> `head(surveys)`, keeping just the first through 6th rows of the surveys
> dataset.
>
> ```{r, answer=TRUE, purl=FALSE}
> ## 1.
> surveys_200 <- surveys[200, ]
> ## 2.
> # Saving `n_rows` to improve readability and reduce duplication
> n_rows <- nrow(surveys)
> surveys_last <- surveys[n_rows, ]
> ## 3.
> surveys_middle <- surveys[n_rows / 2, ]
> ## 4.
> surveys_head <- surveys[-(7:n_rows), ]
> ```
```{r, echo=FALSE, purl=TRUE}
### Challenges:
###
### 1. Create a `data.frame` (`surveys_200`) containing only the
### data in row 200 of the `surveys` dataset.
###
### 2. Notice how `nrow()` gave you the number of rows in a `data.frame`?
###
### * Use that number to pull out just that last row in the data frame
### * Compare that with what you see as the last row using `tail()` to make
### sure it's meeting expectations.
### * Pull out that last row using `nrow()` instead of the row number
### * Create a new data frame object (`surveys_last`) from that last row
###
### 3. Use `nrow()` to extract the row that is in the middle of the
### data frame. Store the content of this row in an object named
### `surveys_middle`.
###
### 4. Combine `nrow()` with the `-` notation above to reproduce the behavior of
### `head(surveys)`, keeping just the first through 6th rows of the surveys
### dataset.
```
## Factors
```{r, echo=FALSE, purl=TRUE}
### Factors
```
When we did `str(surveys)` we saw that several of the columns consist of
integers. The columns `genus`, `species`, `sex`, `plot_type`, ... however, are
of the class `character`.
Arguably, these columns contain categorical data, that is, they can only take on
a limited number of values.
R has a special class for working with categorical data, called `factor`.
Factors are very useful and actually contribute to making R particularly well
suited to working with data. So we are going to spend a little time introducing
them.
Once created, factors can only contain a pre-defined set of values, known as
*levels*.
Factors are stored as integers associated with labels and they can be ordered or unordered. While factors look (and often behave) like character vectors, they are actually treated as integer vectors by R. So you need to be very careful when treating them as strings.
When importing a data frame with `read_csv()`, the columns that contain text are not automatically coerced (=converted) into the `factor` data type, but once we have
loaded the data we can do the conversion using the `factor()` function:
```{r, purl=FALSE}
surveys$sex <- factor(surveys$sex)
```
We can see that the conversion has worked by using the `summary()`
function again. This produces a table with the counts for each factor level:
```{r, purl=FALSE}
summary(surveys$sex)
```
By default, R always sorts levels in alphabetical order. For
instance, if you have a factor with 2 levels:
```{r, purl=TRUE}
sex <- factor(c("male", "female", "female", "male"))
```
R will assign `1` to the level `"female"` and `2` to the level `"male"` (because
`f` comes before `m`, even though the first element in this vector is
`"male"`). You can see this by using the function `levels()` and you can find the
number of levels using `nlevels()`:
```{r, purl=FALSE}
levels(sex)
nlevels(sex)
```
Sometimes, the order of the factors does not matter, other times you might want
to specify the order because it is meaningful (e.g., "low", "medium", "high"),
it improves your visualization, or it is required by a particular type of
analysis. Here, one way to reorder our levels in the `sex` vector would be:
```{r, results=TRUE, purl=FALSE}
sex # current order
sex <- factor(sex, levels = c("male", "female"))
sex # after re-ordering
```
In R's memory, these factors are represented by integers (1, 2, 3), but are more
informative than integers because factors are self describing: `"female"`,
`"male"` is more descriptive than `1`, `2`. Which one is "male"? You wouldn't
be able to tell just from the integer data. Factors, on the other hand, have
this information built in. It is particularly helpful when there are many levels
(like the species names in our example dataset).
> ### Challenge
>
> 1. Change the columns `taxa` and `genus` in the `surveys` data frame into a
> factor.
>
> 2. Using the functions you learned before, can you find out...
>
> * How many rabbits were observed?
> * How many different genera are in the `genus` column?
>
> ```{r, answer=TRUE, purl=FALSE}
> surveys$genus <- factor(surveys$genus)
> summary(surveys)
> nlevels(surveys$genus)
>
> ## * how many genera: There are 26 unique genera in the `genus` column.
> ## * how many rabbts: There are 75 rabbits in the `taxa` column.
> ```
```{r, echo=FALSE, purl=TRUE}
### Challenges:
###
### 1. Change the columns `taxa` and `genus` in the `surveys` data frame into a
### factor.
###
### 2. Using the functions you learned before, can you find out...
###
### * How many rabbits were observed?
### * How many different genera are in the `genus` column?
```
### Converting factors
If you need to convert a factor to a character vector, you use
`as.character(x)`.
```{r, purl=FALSE}
as.character(sex)
```
In some cases, you may have to convert factors where the levels appear as
numbers (such as concentration levels or years) to a numeric vector. For
instance, in one part of your analysis the years might need to be encoded as
factors (e.g., comparing average weights across years) but in another part of
your analysis they may need to be stored as numeric values (e.g., doing math
operations on the years). This conversion from factor to numeric is a little
trickier. The `as.numeric()` function returns the index values of the factor,
not its levels, so it will result in an entirely new (and unwanted in this case)
set of numbers. One method to avoid this is to convert factors to characters,
and then to numbers.
Another method is to use the `levels()` function. Compare:
```{r, purl=TRUE}
year_fct <- factor(c(1990, 1983, 1977, 1998, 1990))
as.numeric(year_fct) # Wrong! And there is no warning...
as.numeric(as.character(year_fct)) # Works...
as.numeric(levels(year_fct))[year_fct] # The recommended way.
```
Notice that in the `levels()` approach, three important steps occur:
* We obtain all the factor levels using `levels(year_fct)`
* We convert these levels to numeric values using `as.numeric(levels(year_fct))`
* We then access these numeric values using the underlying integers of the
vector `year_fct` inside the square brackets
### Renaming factors
When your data is stored as a factor, you can use the `plot()` function to get a
quick glance at the number of observations represented by each factor
level. Let's look at the number of males and females captured over the course of
the experiment:
```{r, purl=TRUE}
## bar plot of the number of females and males captured during the experiment:
plot(surveys$sex)
```
However, as we saw when we used `summary(surveys$sex)`, there are about 1700
individuals for which the sex information hasn't been recorded. To show them in
the plot, we can turn the missing values into a factor level with the
`addNA()` function. We will also have to give the new factor level a label.
We are going to work with a copy of the `sex` column, so we're not modifying the
working copy of the data frame:
```{r, results=TRUE, purl=FALSE}
sex <- surveys$sex
levels(sex)
sex <- addNA(sex)
levels(sex)
head(sex)
levels(sex)[3] <- "undetermined"
levels(sex)
head(sex)
```
Now we can plot the data again, using `plot(sex)`.
```{r echo=FALSE, purl=FALSE, results=TRUE}
plot(sex)
```
> ### Challenge
>
> * Rename "F" and "M" to "female" and "male" respectively.
> * Now that we have renamed the factor level to "undetermined", can you recreate the barplot such that "undetermined" is first (before "female")?
>
> ```{r, answer=TRUE, purl=FALSE}
> levels(sex)[1:2] <- c("female", "male")
> sex <- factor(sex, levels = c("undetermined", "female", "male"))
> plot(sex)
> ```
```{r wrong-order, results='show', echo=FALSE, purl=TRUE}
## Challenges
##
## * Rename "F" and "M" to "female" and "male" respectively.
## * Now that we have renamed the factor level to "undetermined", can you recreate the
## barplot such that "undetermined" is first (before "female")
```
> ### Challenge
>
> 1. We have seen how data frames are created when using `read_csv()`, but
> they can also be created by hand with the `data.frame()` function. There are
> a few mistakes in this hand-crafted `data.frame`. Can you spot and fix them?
> Don't hesitate to experiment!
>
> ```{r, eval=FALSE, purl=FALSE}
> animal_data <- data.frame(
> animal = c(dog, cat, sea cucumber, sea urchin),
> feel = c("furry", "squishy", "spiny"),
> weight = c(45, 8 1.1, 0.8)
> )
> ```
>
> ```{r, eval=FALSE, purl=TRUE, echo=FALSE}
> ## Challenge:
> ## There are a few mistakes in this hand-crafted `data.frame`,
> ## can you spot and fix them? Don't hesitate to experiment!
> animal_data <- data.frame(
> animal = c(dog, cat, sea cucumber, sea urchin),
> feel = c("furry", "squishy", "spiny"),
> weight = c(45, 8 1.1, 0.8)
> )
> ```
>
> 2. Can you predict the class for each of the columns in the following example?
> Check your guesses using `str(country_climate)`:
> * Are they what you expected? Why? Why not?
> * What would you need to change to ensure that each column had the accurate data type?
>
> ```{r, eval=FALSE, purl=FALSE}
> country_climate <- data.frame(
> country = c("Canada", "Panama", "South Africa", "Australia"),
> climate = c("cold", "hot", "temperate", "hot/temperate"),
> temperature = c(10, 30, 18, "15"),
> northern_hemisphere = c(TRUE, TRUE, FALSE, "FALSE"),
> has_kangaroo = c(FALSE, FALSE, FALSE, 1)
> )
> ```
>
> ```{r, eval=FALSE, purl=TRUE, echo=FALSE}
> ## Challenge:
> ## Can you predict the class for each of the columns in the following
> ## example?
> ## Check your guesses using `str(country_climate)`:
> ## * Are they what you expected? Why? why not?
> ## * What would you need to change to ensure that each column had the
> ## accurate data type?
> country_climate <- data.frame(country = c("Canada", "Panama", "South Africa", "Australia"),
> climate = c("cold", "hot", "temperate", "hot/temperate"),
> temperature = c(10, 30, 18, "15"),
> northern_hemisphere = c(TRUE, TRUE, FALSE, "FALSE"),
> has_kangaroo = c(FALSE, FALSE, FALSE, 1))
> ```
>
> ```{text_answer, echo=FALSE, purl=FALSE}
> * missing quotations around the names of the animals
> * missing one entry in the `feel` column (probably for one of the furry animals)
> * missing one comma in the `weight` column
> * `country`, `climate`, `temperature`, and `northern_hemisphere` are
> characters; `has_kangaroo` is numeric
> * using `factor()` one could replace character columns with factors columns
> * removing the quotes in `temperature` and `northern_hemisphere` and replacing 1
> by TRUE in the `has_kangaroo` column would give what was probably
> intended
> ```
>
The automatic conversion of data type is sometimes a blessing, sometimes an
annoyance. Be aware that it exists, learn the rules, and double check that data
you import in R are of the correct type within your data frame. If not, use it
to your advantage to detect mistakes that might have been introduced during data
entry (for instance, a letter in a column that should only contain numbers).
Learn more in this [RStudio tutorial](https://support.rstudio.com/hc/en-us/articles/218611977-Importing-Data-with-RStudio)
## Formatting dates
One of the most common issues that new (and experienced!) R users have is
converting date and time information into a variable that is appropriate and
usable during analyses. As a reminder from earlier in this lesson, the best
practice for dealing with date data is to ensure that each component of your
date is stored as a separate variable. Using `str()`, We can confirm that our
data frame has a separate column for day, month, and year, and that each contains
integer values.
```{r, eval=FALSE, purl=FALSE}
str(surveys)
```
We are going to use the `ymd()` function from the package **`lubridate`** (which belongs to the **`tidyverse`**; learn more [here](https://www.tidyverse.org/)). **`lubridate`** gets installed as part as the **`tidyverse`** installation. When you load the **`tidyverse`** (`library(tidyverse)`), the core packages (the packages used in most data analyses) get loaded. **`lubridate`** however does not belong to the core tidyverse, so you have to load it explicitly with `library(lubridate)`
Start by loading the required package:
```{r load-package, message=FALSE, purl=FALSE}
library(lubridate)
```
`ymd()` takes a vector representing year, month, and day, and converts it to a
`Date` vector. `Date` is a class of data recognized by R as being a date and can
be manipulated as such. The argument that the function requires is flexible,
but, as a best practice, is a character vector formatted as "YYYY-MM-DD".
Let's create a date object and inspect the structure:
```{r, purl=FALSE}
my_date <- ymd("2015-01-01")
str(my_date)
```
Now let's paste the year, month, and day separately - we get the same result:
```{r, purl=FALSE}
# sep indicates the character to use to separate each component
my_date <- ymd(paste("2015", "1", "1", sep = "-"))
str(my_date)
```
Now we apply this function to the surveys dataset. Create a character vector from the `year`, `month`, and `day` columns of
`surveys` using `paste()`:
```{r, purl=FALSE}
paste(surveys$year, surveys$month, surveys$day, sep = "-")
```
This character vector can be used as the argument for `ymd()`:
```{r, purl=FALSE}
ymd(paste(surveys$year, surveys$month, surveys$day, sep = "-"))
```
There is a warning telling us that some dates could not be parsed (understood)
by the `ymd()` function. For these dates, the function has returned `NA`, which
means they are treated as missing values.
We will deal with this problem later, but first we add the resulting `Date`
vector to the `surveys` data frame as a new column called `date`:
```{r, purl=FALSE}
surveys$date <- ymd(paste(surveys$year, surveys$month, surveys$day, sep = "-"))
str(surveys) # notice the new column, with 'date' as the class
```
Let's make sure everything worked correctly. One way to inspect the new column is to use `summary()`:
```{r, results=TRUE, purl=FALSE}
summary(surveys$date)
```
Let's investigate why some dates could not be parsed.
We can use the functions we saw previously to deal with missing data to identify
the rows in our data frame that are failing. If we combine them with what we learned about subsetting data frames earlier, we can extract the columns "year, "month", "day" from the records that have `NA` in our new column `date`. We will also use `head()` so we don't clutter the output:
```{r, results=TRUE, purl=FALSE}
missing_dates <- surveys[is.na(surveys$date), c("year", "month", "day")]
head(missing_dates)
```
Why did these dates fail to parse? If you had to use these data for your
analyses, how would you deal with this situation?
```{r, child="_page_built_on.Rmd"}
```