forked from lgatto/2017_11_09_Rcourse_Jena
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23-dplyr.Rmd
671 lines (526 loc) · 24.8 KB
/
23-dplyr.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
# Manipulating and analyzing data
> The following material is based on Data Carpentry's the
> [Data analisis and visualisation](http://www.datacarpentry.org/R-ecology-lesson/) lessons.
Learning Objectives:
* Understand the purpose of the **`dplyr`** and **`tidyr`** packages.
* Select certain columns in a data frame with the **`dplyr`** function `select`.
* Select certain rows in a data frame according to filtering
conditions with the **`dplyr`** function `filter` .
* Link the output of one **`dplyr`** function to the input of another function with the 'pipe' operator.
* Add new columns to a data frame that are functions of existing columns with `mutate`.
* Understand the split-apply-combine concept for data analysis.
* Use `summarize`, `group_by`, and `tally` to split a data frame into groups
of observations, apply a summary statistics for each group, and then
combine the results.
* Understand the concept of a wide and a long table format and for which purpose those formats are useful.
* Understand what key-value pairs are.
* Reshape a data frame from long to wide format and back with the
`spread` and `gather` commands from the **`tidyr`** package.
* Export a data frame to a .csv file.
Bracket subsetting is handy, but it can be cumbersome and difficult to
read, especially for complicated operations. Enter
**`dplyr`**. **`dplyr`** is a package for making tabular data manipulation
easier. It pairs nicely with **`tidyr`** which enables you to swiftly
convert between different data formats for plotting and analysis.
Packages in R are basically sets of additional functions that let you do more
stuff. The functions we've been using so far, like `str()` or `data.frame()`,
come built into R; packages give you access to more of them. 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. You should
already have installed the **`tidyverse`** package. This is an
"umbrella-package" that installs several packages useful for data analysis which
work together well such as **`tidyr`**, **`dplyr`**, **`ggplot2`**, **`tibble`**, etc.
**`tidyverse`** package tries to address 3 major problems with some of base R functions:
1. The results from a base R function sometimes depends on the type of data.
2. Using R expressions in a non standard way, which can be confusing for new learners.
3. Hidden arguments, having default operations that new learners are not aware of.
We have seen in our previous lesson that when building or importing a
data frame, the columns that contain characters (i.e., text) are
coerced (=converted) into the factor data type. We had to set
**`stringsAsFactor`** to **`FALSE`** to avoid this hidden argument to
convert our data type.
This time will use the **`tidyverse`** package to read the data and
avoid having to set **`stringsAsFactor`** to **`FALSE`**
To load the package type:
```{r, message = FALSE, purl = FALSE}
library("tidyverse") ## load the tidyverse packages, incl. dplyr
```
## What are **`dplyr`** and **`tidyr`**?
The package **`dplyr`** provides easy tools for the most common data manipulation
tasks. It is built to work directly with data frames, with many common tasks
optimized by being written in a compiled language (C++). An additional feature is the
ability to work directly with data stored in an external database. The benefits of
doing this are that the data can be managed natively in a relational database,
queries can be conducted on that database, and only the results of the query are
returned.
This addresses a common problem with R in that all operations are conducted
in-memory and thus the amount of data you can work with is limited by available
memory. The database connections essentially remove that limitation in that you
can have a database of many 100s GB, conduct queries on it directly, and pull
back into R only what you need for analysis.
The package **`tidyr`** addresses the common problem of wanting to
reshape your data for plotting and use by different R
functions. Sometimes we want data sets where we have one row per
measurement. Sometimes we want a data frame where each measurement
type has its own column, and rows are instead more aggregated groups -
like plots or aquaria. Moving back and forth between these formats is
nontrivial, and **`tidyr`** gives you tools for this and more
sophisticated data manipulation.
To learn more about **`dplyr`** and **`tidyr`** after the workshop,
you may want to check out
this
[handy data transformation with **`dplyr`** cheatsheet](https://github.com/rstudio/cheatsheets/raw/master/data-transformation.pdf) and
this
[one about **`tidyr`**](https://github.com/rstudio/cheatsheets/raw/master/data-import.pdf).
**`dplyr`** reads data using read_csv(), instead of read.csv()
```{r,results = 'hide', purl = FALSE}
surveys <- read_csv('data/portal_data_joined.csv')
## inspect the data
str(surveys)
```
Notice that the class of the data is now `tbl_df` This is referred to
as a "tibble" Tibbles are data frames, but they tweak some of the old
behaviors of data frames. The data structure is very similar to a data
frame. For our purposes the only differences are that:
1. In addition to displaying the data type of each column under its
name, it only prints the first few rows of data and only as many
columns as fit on one screen.
2. Columns of class `character` are never converted into factors.
## Selecting columns and filtering rows
We're going to learn some of the most common **`dplyr`** functions: `select()`,
`filter()`, `mutate()`, `group_by()`, and `summarize()`. To select columns of a
data frame, use `select()`. The first argument to this function is the data
frame (`surveys`), and the subsequent arguments are the columns to keep.
```{r, results = 'hide', purl = FALSE}
select(surveys, plot_id, species_id, weight)
```
To choose rows based on a specific criteria, use `filter()`:
```{r, purl = FALSE}
filter(surveys, year == 1995)
```
## Pipes
But what if you wanted to select and filter at the same time? There are three
ways to do this: use intermediate steps, nested functions, or pipes.
With intermediate steps, you essentially create a temporary data frame and use
that as input to the next function. This can clutter up your workspace with lots
of objects. You can also nest functions (i.e. one function inside of another).
This is handy, but can be difficult to read if too many functions are nested as
things are evaluated from the inside out.
The last option, pipes, are a fairly recent addition to R. Pipes let you take
the output of one function and send it directly to the next, which is useful
when you need to do many things to the same dataset. Pipes in R look like
`%>%` and are made available via the `magrittr` package, installed automatically
with **`dplyr`**. If you use RStudio, you can type the pipe with <kbd>Ctrl</kbd>
+ <kbd>Shift</kbd> + <kbd>M</kbd> if you have a PC or <kbd>Cmd</kbd> +
<kbd>Shift</kbd> + <kbd>M</kbd> if you have a Mac.
```{r, purl = FALSE}
surveys %>%
filter(weight < 5) %>%
select(species_id, sex, weight)
```
In the above, we use the pipe to send the `surveys` dataset first through
`filter()` to keep rows where `weight` is less than 5, then through `select()`
to keep only the `species_id`, `sex`, and `weight` columns. Since `%>%` takes
the object on its left and passes it as the first argument to the function on
its right, we don't need to explicitly include it as an argument to the
`filter()` and `select()` functions anymore.
If we wanted to create a new object with this smaller version of the data, we
could do so by assigning it a new name:
```{r, purl = FALSE}
surveys_sml <- surveys %>%
filter(weight < 5) %>%
select(species_id, sex, weight)
surveys_sml
```
Note that the final data frame is the leftmost part of this expression.
> Challenge {.challenge}
>
> Using pipes, subset the `surveys` data to include individuals collected before
> 1995 and retain only the columns `year`, `sex`, and `weight`.
<details>
```{r, eval=FALSE, purl=FALSE}
## Answer
surveys %>%
filter(year < 1995) %>%
select(year, sex, weight)
```
</details>
## Mutate
Frequently you'll want to create new columns based on the values in existing
columns, for example to do unit conversions, or find the ratio of values in two
columns. For this we'll use `mutate()`.
To create a new column of weight in kg:
```{r, purl = FALSE}
surveys %>%
mutate(weight_kg = weight / 1000)
```
You can also create a second new column based on the first new column within the same call of `mutate()`:
```{r, purl = FALSE}
surveys %>%
mutate(weight_kg = weight / 1000,
weight_kg2 = weight_kg * 2)
```
If this runs off your screen and you just want to see the first few rows, you
can use a pipe to view the `head()` of the data. (Pipes work with non-**`dplyr`**
functions, too, as long as the **`dplyr`** or `magrittr` package is loaded).
```{r, purl = FALSE}
surveys %>%
mutate(weight_kg = weight / 1000) %>%
head
```
Note that we don't include parentheses at the end of our call to `head()` above.
When piping into a function with no additional arguments, you can call the
function with or without parentheses (e.g. `head` or `head()`).
The first few rows of the output are full of `NA`s, so if we wanted to remove
those we could insert a `filter()` in the chain:
```{r, purl = FALSE}
surveys %>%
filter(!is.na(weight)) %>%
mutate(weight_kg = weight / 1000) %>%
head
```
`is.na()` is a function that determines whether something is an `NA`. The `!`
symbol negates the result, so we're asking for everything that *is not* an `NA`.
> Challenge {.challenge}
>
> Create a new data frame from the `surveys` data that meets the following
> criteria: contains only the `species_id` column and a new column called
> `hindfoot_half` containing values that are half the `hindfoot_length` values.
> In this `hindfoot_half` column, there are no `NA`s and all values are less
> than 30.
>
> **Hint**: think about how the commands should be ordered to produce this data frame!
<details>
```{r, eval=FALSE, purl=FALSE}
surveys_hindfoot_half <- surveys %>%
filter(!is.na(hindfoot_length)) %>%
mutate(hindfoot_half = hindfoot_length / 2) %>%
filter(hindfoot_half < 30) %>%
select(species_id, hindfoot_half)
```
</details>
## Split-apply-combine data analysis and the summarize() function
Many data analysis tasks can be approached using the *split-apply-combine*
paradigm: split the data into groups, apply some analysis to each group, and
then combine the results. **`dplyr`** makes this very easy through the use of the
`group_by()` function.
### The `summarize()` function
`group_by()` is often used together with `summarize()`, which collapses each
group into a single-row summary of that group. `group_by()` takes as arguments
the column names that contain the **categorical** variables for which you want
to calculate the summary statistics. So to view the mean `weight` by sex:
```{r, purl = FALSE}
surveys %>%
group_by(sex) %>%
summarize(mean_weight = mean(weight, na.rm = TRUE))
```
You may also have noticed that the output from these calls doesn't run off the
screen anymore. It's one of the advantages of `tbl_df` over data frame.
You can also group by multiple columns:
```{r, purl = FALSE}
surveys %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight, na.rm = TRUE))
```
When grouping both by `sex` and `species_id`, the first rows are for individuals
that escaped before their sex could be determined and weighted. You may notice
that the last column does not contain `NA` but `NaN` (which refers to "Not a
Number"). To avoid this, we can remove the missing values for weight before we
attempt to calculate the summary statistics on weight. Because the missing
values are removed, we can omit `na.rm = TRUE` when computing the mean:
```{r, purl = FALSE}
surveys %>%
filter(!is.na(weight)) %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight))
```
Here, again, the output from these calls doesn't run off the screen
anymore. If you want to display more data, you can use the `print()` function
at the end of your chain with the argument `n` specifying the number of rows to
display:
```{r, purl = FALSE}
surveys %>%
filter(!is.na(weight)) %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight)) %>%
print(n = 15)
```
Once the data are grouped, you can also summarize multiple variables at the same
time (and not necessarily on the same variable). For instance, we could add a
column indicating the minimum weight for each species for each sex:
```{r, purl = FALSE}
surveys %>%
filter(!is.na(weight)) %>%
group_by(sex, species_id) %>%
summarize(mean_weight = mean(weight),
min_weight = min(weight))
```
### Tallying
When working with data, it is also common to want to know the number of
observations found for each factor or combination of factors. For this, **`dplyr`**
provides `tally()`. For example, if we wanted to group by sex and find the
number of rows of data for each sex, we would do:
```{r, purl = FALSE}
surveys %>%
group_by(sex) %>%
tally
```
Here, `tally()` is the action applied to the groups created by `group_by()` and
counts the total number of records for each category.
> Challenge {.challenge}
>
> 1. How many individuals were caught in each `plot_type` surveyed?
>
> 2. Use `group_by()` and `summarize()` to find the mean, min, and max hindfoot
> length for each species (using `species_id`).
>
> 3. What was the heaviest animal measured in each year? Return the columns `year`,
> `genus`, `species_id`, and `weight`.
>
> 4. You saw above how to count the number of individuals of each `sex` using a
> combination of `group_by()` and `tally()`. How could you get the same result
> using `group_by()` and `summarize()`? Hint: see `?n`.
<details>
```{r}
## Answer 1
surveys %>%
group_by(plot_type) %>%
tally
## Answer 2
surveys %>%
filter(!is.na(hindfoot_length)) %>%
group_by(species_id) %>%
summarize(
mean_hindfoot_length = mean(hindfoot_length),
min_hindfoot_length = min(hindfoot_length),
max_hindfoot_length = max(hindfoot_length)
)
## Answer 3
surveys %>%
filter(!is.na(weight)) %>%
group_by(year) %>%
filter(weight == max(weight)) %>%
select(year, genus, species, weight) %>%
arrange(year)
## Answer 4
surveys %>%
group_by(sex) %>%
summarize(n = n())
```
</details>
## Reshaping with gather and spread
In the
<span style="background:yellow">[spreadsheet lesson](http://www.datacarpentry.org/spreadsheet-ecology-lesson/01-format-data/)</span> we discussed how to
structure our data leading to the four rules defining a tidy dataset:
1. Each variable has its own column
2. Each observation has its own row
3. Each value must have its own cell
4. Each type of observational unit forms a table
Here we examine the fourth rule: Each type of observational unit forms a table.
In `surveys` , the rows of `surveys` contain the values of variables associated
with each record (the unit), values such the weight or sex of each animal
associated with each record. What if instead of comparing records, we
wanted to compare the different mean weight of each species between plots? (Ignoring `plot_type` for simplicity).
We'd need to create a new table where each row (the unit) comprises of values of variables associated with each plot. In practical terms this means the values
of the species in `genus` would become the names of column variables and the cells would contain the values of the mean weight observed on each plot.
Having created a new table, it is therefore straightforward to explore the
relationship between the weight of different species within, and between, the
plots. The key point here is that we are still following a tidy data structure,
but we have **reshaped** the data according to the observations of interest:
average species weight per plot instead of recordings per date.
The opposite transformation would be to transform column names into values of
a variable.
We can do both these of transformations with two `tidyr` functions, `spread()`
and `gather()`.
#### Spreading {-}
`spread()` takes three principal arguments:
1. the data
2. the *key* column variable whose values will become new column names.
3. the *value* column variable whose values will fill the new column variables.
Further arguements include `fill` which if set, fills in missing values with
that provided.
Let's use `spread()` to transform surveys to find the mean weight of each
species in each plot over the entire survey period. We use `filter()`,
`group_by()` and `summarise()` to filter our observations and variables of
interest, and create a new variable for the `mean_weight`. We use the pipe as
before too.
```{r, purl=FALSE}
surveys_gw <- surveys %>%
filter(!is.na(weight)) %>%
group_by(genus, plot_id) %>%
summarize(mean_weight = mean(weight))
str(surveys_gw)
```
This yields `surveys_gw` where the observation for each plot is spread across
multiple rows, 196 observations of 13 variables.
Using `spread()` to key on `genus` with values from `mean_weight` this becomes
24 observations of 11 variables, one row for each plot. We use the pipe as
before too.
```{r, purl=FALSE}
surveys_spread <- surveys_gw %>%
spread(key = genus, value = mean_weight)
str(surveys_spread)
```
![](./figs/spread_data_R.png)
We could now plot comparisons between the weight of species on different plots
for example, although we may wish to fill in the missing values first.
```{r, purl=FALSE}
surveys_gw %>%
spread(genus, mean_weight, fill = 0) %>%
head()
```
#### Gathering {-}
The opposing situation could occur if we had been provided with data in the
form of `surveys_spread`, where the genus names are column names, but we
wish to treat them as values of a genus variable instead.
In this situation we are gathering the column names and turning them into a
pair of new variables. One variable represents the column names as values, and
the other variable contains the values previously associated with the column names.
`gather()` takes four principal arguments:
1. the data
2. the *key* column variable we wish to create from column names.
3. the *values* column variable we wish to create and fill with values
associated with the key.
4. the names of the columns we use to fill the key variable (or to drop).
To recreate `surveys_gw` from `surveys_spread` we would create a key called
`genus` and value called `mean_weight` and use all columns except `plot_id` for
the key variable. Here we drop `plot_id` column with a minus sign.
```{r, purl=FALSE}
surveys_gather <- surveys_spread %>%
gather(key = genus, value = mean_weight, -plot_id)
str(surveys_gather)
```
![](./figs/gather_data_R.png)
Note that now the `NA` genera are included in the re-gathered format. Spreading
and then gathering can be a useful way to balance out a dataset so every
replicate has the same composition.
We could also have used a specification for what columns to include. This can be
useful if you have a large number of identifying columns, and it's easier to
specify what to gather than what to leave alone. And if the columns are in a
row, we don't even need to list them all out - just use the `:` operator!
```{r, purl=FALSE}
surveys_spread %>%
gather(key = genus, value = mean_weight, Baiomys:Spermophilus) %>%
head()
```
> Challenge {.challenge}
>
> 1. Spread the data frame with `year` as columns, `plot_id` as rows, and the
> values are the number of genera per plot. You will need to summarize before
> reshaping, and use the function `n_distinct()` to get the number of unique
> types of a genera. It's a powerful function! See `?n_distinct` for more.
>
> 2. Now take that data frame, and make gather it again, so each row is a unique
> `plot_id` `year` combination.
>
> 3. The `surveys` data set has
> two columns of measurement: `hindfoot_length` and `weight`. This makes it
> difficult to do things like look at the relationship between mean values of
> each measurement per year in different plot types. Let's walk through a
> common solution for this type of problem. First, use `gather()` to create a
> dataset where we have a key column called `measurement` and a
> `value` column that takes on the value of either `hindfoot_length` or
> `weight`. Hint: You'll need to specify which columns are being gathered.
>
> 4. With this new data set, calculate the average of each
> `measurement` in each `year` > for each different `plot_type`. Then
> `spread()` them into a data set with a column for `hindfoot_length` and
> `weight`. Hint: Remember, you only need to specify the key and value
> columns for `spread()`.
<details>
```{r, echo=FALSE, purl=FALSE}
## Answer 1
rich_time <- surveys %>%
group_by(plot_id, year) %>%
summarize(n_genera = n_distinct(genus)) %>%
spread(year, n_genera)
head(rich_time)
## Answer 2
rich_time %>%
gather(year, n_genera, -plot_id)
## Answer 3
surveys_long <- surveys %>%
gather(measurement, value, hindfoot_length, weight)
## Answer 4
surveys_long %>%
group_by(year, measurement, plot_type) %>%
summarize(mean_value = mean(value, na.rm=TRUE)) %>%
spread(measurement, mean_value)
```
</details>
## Exporting data
Now that you have learned how to use **`dplyr`** to extract information from
or summarize your raw data, you may want to export these new datasets to share
them with your collaborators or for archival.
Similar to the `read_csv()` function used for reading CSV files into R, there is
a `write_csv()` function that generates CSV files from data frames.
Before using `write_csv()`, we are going to create a new folder, `data_output`,
in our working directory that will store this generated dataset. We don't want
to write generated datasets in the same directory as our raw data. It's good
practice to keep them separate. The `data` folder should only contain the raw,
unaltered data, and should be left alone to make sure we don't delete or modify
it. In contrast, our script will generate the contents of the `data_output`
directory, so even if the files it contains are deleted, we can always
re-generate them.
In preparation for our next lesson on plotting, we are going to prepare a
cleaned up version of the dataset that doesn't include any missing data.
Let's start by removing observations for which the `species_id` is missing. In
this dataset, the missing species are represented by an empty string and not an
`NA`. Let's also remove observations for which `weight` and the
`hindfoot_length` are missing. This dataset should also only contain
observations of animals for which the sex has been determined:
```{r, purl=FALSE}
surveys_complete <- surveys %>%
filter(species_id != "", # remove missing species_id
!is.na(weight), # remove missing weight
!is.na(hindfoot_length), # remove missing hindfoot_length
sex != "") # remove missing sex
```
Because we are interested in plotting how species abundances have changed
through time, we are also going to remove observations for rare species (i.e.,
that have been observed less than 50 times). We will do this in two steps: first
we are going to create a dataset that counts how often each species has been
observed, and filter out the rare species; then, we will extract only the
observations for these more common species:
```{r, purl=FALSE}
## Extract the most common species_id
species_counts <- surveys_complete %>%
group_by(species_id) %>%
tally %>%
filter(n >= 50)
## Only keep the most common species
surveys_complete <- surveys_complete %>%
filter(species_id %in% species_counts$species_id)
```
```{r, eval=FALSE, purl=TRUE, echo=FALSE}
### Create the dataset for exporting:
## Start by removing observations for which the `species_id`, `weight`,
## `hindfoot_length`, or `sex` data are missing:
surveys_complete <- surveys %>%
filter(species_id != "", # remove missing species_id
!is.na(weight), # remove missing weight
!is.na(hindfoot_length), # remove missing hindfoot_length
sex != "") # remove missing sex
## Now remove rare species in two steps. First, make a list of species which
## appear at least 50 times in our dataset:
species_counts <- surveys_complete %>%
group_by(species_id) %>%
tally %>%
filter(n >= 50) %>%
select(species_id)
## Second, keep only those species:
surveys_complete <- surveys_complete %>%
filter(species_id %in% species_counts$species_id)
```
To make sure that everyone has the same dataset, check that `surveys_complete`
has `r nrow(surveys_complete)` rows and `r ncol(surveys_complete)` columns by
typing `dim(surveys_complete)`.
Now that our dataset is ready, we can save it as a CSV file in our `data_output`
folder.
```{r, purl=FALSE, eval=FALSE}
write_csv(surveys_complete, path = "data/surveys_complete.csv")
```
```{r, purl=FALSE, eval=TRUE, echo=FALSE}
if (!file.exists("data")) dir.create("data")
write_csv(surveys_complete, path = "data/surveys_complete.csv")
```