-
Notifications
You must be signed in to change notification settings - Fork 4
/
06-tidyr.Rmd
672 lines (477 loc) · 26.7 KB
/
06-tidyr.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
# Tidy Data {#tidyr}
<div class="right meme"><img src="images/memes/messy_data.jpg"
alt="A giant demon emerging from fire labelled 'messy data'; in front is a tiny human labelled 'R User'" /></div>
## Learning Objectives {#ilo-tidyr}
### Basic {-}
1. Understand the concept of [tidy data](#tidy-data) [(video)](https://youtu.be/EsSN4OdsNpc){class="video"}
2. Be able to convert between long and wide formats using pivot functions [(video)](https://youtu.be/4dvLmjhwN8I){class="video"}
+ [`pivot_longer()`](#pivot_longer)
+ [`pivot_wider()`](#pivot_wider)
3. Be able to use the 4 basic `tidyr` verbs [(video)](https://youtu.be/oUWjb0JC8zM){class="video"}
+ [`gather()`](#gather)
+ [`separate()`](#separate)
+ [`spread()`](#spread)
+ [`unite()`](#unite)
4. Be able to chain functions using [pipes](#pipes) [(video)](https://youtu.be/itfrlLaN4SE){class="video"}
### Intermediate {-}
5. Be able to use [regular expressions](#regex) to separate complex columns
## Setup {#setup-tidyr}
1. Open your `reprores-class-notes` project
1. Create a new R Markdown file called `06-tidyr.Rmd`
1. Update the YAML header
1. Replace the setup chunk with the one below:
```{r setup-tidyr, results = 'hide', warning = FALSE, message = FALSE, verbatim = "r setup, include = FALSE"}
knitr::opts_chunk$set(echo = TRUE)
# packages needed for this chapter
library(tidyverse) # loads tidyr for pivot functions and tidy verbs
library(reprores) # class-specific datasets
set.seed(8675309) # makes sure random numbers are reproducible
```
Download the [Data tidying cheat sheet](https://raw.githubusercontent.com/rstudio/cheatsheets/main/tidyr.pdf).
## Tidy Data {#tidy-data}
### Three Rules
* Each `r glossary("variable")` must have its own column
* Each `r glossary("observation")` must have its own row
* Each `r glossary("value")` must have its own cell
```{r, echo = FALSE}
untidy <- data.frame(
id = 1:5,
score_1 = sample(1:7, 5),
score_2 = sample(1:7, 5),
score_3 = sample(1:7, 5),
rt_1 = rnorm(5, 800, 100) |> round(),
rt_2 = rnorm(5, 800, 100) |> round(),
rt_3 = rnorm(5, 800, 100) |> round()
) |>
mutate(
total = score_1 + score_2 + score_3,
mean_rt = round((rt_1 + rt_2 + rt_3)/3),
total_meanRT = paste0(total, " (", mean_rt, ")")
) |>
select(-total, -mean_rt)
tidy <- untidy |>
gather(var, val, score_1:rt_3) |>
separate(var, c("var", "trial")) |>
spread(var, val) |>
separate(total_meanRT, c("total", "mean_rt"), extra = "drop") |>
select(id, trial:score, total, mean_rt)
```
This table has three observations per row and the `total_meanRT` column contains two values.
`r knitr::kable(untidy, caption = "Untidy table")`
This is the tidy version.
`r knitr::kable(tidy, caption = "Tidy table")`
### Wide versus long {#wide_long}
Data tables can be in `r glossary("wide")` format or `r glossary("long")` format (and sometimes a mix of the two). Wide data are where all of the observations about one subject are in the same row, while long data are where each observation is on a separate row. You often need to convert between these formats to do different types of analyses or data processing.
Imagine a study where each subject completes a questionnaire with three items. Each answer is an `r glossary("observation")` of that subject. You are probably most familiar with data like this in a wide format, where the subject `id` is in one column, and each of the three item responses is in its own column.
```{r wide-data, echo = FALSE, render = "asis"}
x <- tibble(id = c("A", "B"),
Q1 = c(1,4),
Q2 = c(2,5),
Q3 = c(3,6))
knitr::kable(x, caption = "Wide data")
```
The same data can be represented in a long format by creating a new column that specifies what `item` the observation is from and a new column that specifies the `value` of that observation.
```{r long-data, echo = FALSE, render = "asis"}
gather(x, "item", "value", Q1:Q3) |>
knitr::kable(caption = "Long data")
```
::: {.try data-latex=""}
Create a long version of the following table.
| id | fav_colour | fav_animal |
|:-------|:-----------|:-----------|
| Lisa | red | echidna |
| Robbie | orange | babirusa |
| Steven | green | frog |
`r hide("Answer")`
Your answer doesn't need to have the same column headers or be in the same order.
| id | fav | answer |
|:-------|:------ |:---------|
| Lisa | colour | red |
| Lisa | animal | echidna |
| Robbie | colour | orange |
| Robbie | animal | babirusa |
| Steven | colour | green |
| Steven | animal | frog |
`r unhide()`
:::
## Pivot Functions {#pivot}
The pivot functions allow you to transform a data table from wide to long or long to wide in one step.
### Load Data
We will used the dataset `personality` from the reprores package (or download the data from [personality.csv](./data/personality.csv)). These data are from a 5-factor (personality) personality questionnaire. Each question is labelled with the domain (Op = openness, Co = conscientiousness, Ex = extroversion, Ag = agreeableness, and Ne = neuroticism) and the question number.
```{r load-personality}
data("personality", package = "reprores")
```
`r head(personality) |> knitr::kable()`
### pivot_longer() {#pivot_longer}
`pivot_longer()` converts a wide data table to long format by converting the headers from specified columns into the values of new columns, and combining the values of those columns into a new condensed column.
* `cols` refers to the columns you want to make long You can refer to them by their names, like `col1, col2, col3, col4` or `col1:col4` or by their numbers, like `8, 9, 10` or `8:10`.
* `names_to` is what you want to call the new columns that the gathered column headers will go into; it's "domain" and "qnumber" in this example.
* `names_sep` is an optional argument if you have more than one value for `names_to`. It specifies the characters or position to split the values of the `cols` headers.
* `values_to` is what you want to call the values in the columns `...`; they're "score" in this example.
```{r pivot-longer}
personality_long <- pivot_longer(
data = personality,
cols = Op1:Ex9, # columns to make long
names_to = c("domain", "qnumber"), # new column names for headers
names_sep = 2, # how to split the headers
values_to = "score" # new column name for values
) |>
glimpse()
```
::: {.info data-latex=""}
You can pipe a data table to `glimpse()` at the end to have a quick look at it. It will still save to the object.
:::
::: {.try data-latex=""}
What would you set `names_sep` to in order to split the `cols` headers listed below into the results?
```{r, echo = FALSE}
w1 <- mcq(c("A", "B", "1", "2", answer = "_"))
w2 <- mcq(c("A", "B", answer = "1", "2", "_"))
w3 <- mcq(c("-", "&", answer = "-\\|&", "c(3, 7)"))
```
| `cols` | `names_to` | `names_sep` |
|:---------------------------|:------------|:------------|
| `A_1`, `A_2`, `B_1`, `B_2` | `c("condition", "version")` | `r w1` |
| `A1`, `A2`, `B1`, `B2` | `c("condition", "version")` | `r w2` |
| `cat-day&pre`, `cat-day&post`, `cat-night&pre`, `cat-night&post`, `dog-day&pre`, `dog-day&post`, `dog-night&pre`, `dog-night&post` | `c("pet", "time", "condition")` | `r w3` |
:::
### pivot_wider() {#pivot_wider}
We can also go from long to wide format using the `pivot_wider()` function.
* `names_from` is the columns that contain your new column headers.
* `values_from` is the column that contains the values for the new columns.
* `names_sep` is the character string used to join names if `names_from` is more than one column.
```{r pivot-wider}
personality_wide <- pivot_wider(
data = personality_long,
names_from = c(domain, qnumber),
values_from = score,
names_sep = ""
) |>
glimpse()
```
## Tidy Verbs {#tidy-verbs}
The pivot functions above are relatively new functions that combine the four basic tidy verbs. You can also convert data between long and wide formats using these functions. Many researchers still use these functions and older code will not use the pivot functions, so it is useful to know how to interpret these.
### gather() {#gather}
Much like `pivot_longer()`, `gather()` makes a wide data table long by creating a column for the headers and a column for the values. The main difference is that you cannot turn the headers into more than one column.
* `key` is what you want to call the new column that the gathered column headers will go into; it's "question" in this example. It is like `names_to` in `pivot_longer()`, but can only take one value (multiple values need to be separated after `separate()`).
* `value` is what you want to call the values in the gathered columns; they're "score" in this example. It is like `values_to` in `pivot_longer()`.
* `...` refers to the columns you want to gather. It is like `cols` in `pivot_longer()`.
The `gather()` function converts `personality` from a wide data table to long format, with a row for each user/question observation. The resulting data table should have the columns: `user_id`, `date`, `question`, and `score`.
```{r personality-gathered}
personality_gathered <- gather(
data = personality,
key = "question", # new column name for gathered headers
value = "score", # new column name for gathered values
Op1:Ex9 # columns to gather
) |>
glimpse()
```
### separate() {#separate}
* `col` is the column you want to separate
* `into` is a vector of new column names
* `sep` is the character(s) that separate your new columns. This defaults to anything that isn't alphanumeric, like .`,_-/:` and is like the `names_sep` argument in `pivot_longer()`.
Split the `question` column into two columns: `domain` and `qnumber`.
There is no character to split on, here, but you can separate a column after a specific number of characters by setting `sep` to an integer. For example, to split "abcde" after the third character, use `sep = 3`, which results in `c("abc", "de")`. You can also use negative number to split before the *n*th character from the right. For example, to split a column that has words of various lengths and 2-digit suffixes (like "lisa03"", "amanda38"), you can use `sep = -2`.
```{r personality-separate}
personality_sep <- separate(
data = personality_gathered,
col = question, # column to separate
into = c("domain", "qnumber"), # new column names
sep = 2 # where to separate
) |>
glimpse()
```
::: {.warning data-latex=""}
If you want to separate just at full stops, you need to use `sep = "\\."`, not `sep = "."`. The two slashes **escape** the full stop, making it interpreted as a literal full stop and not the regular expression for any character.
:::
### unite() {#unite}
* `col` is your new united column
* `...` refers to the columns you want to unite
* `sep` is the character(s) that will separate your united columns
Put the domain and qnumber columns back together into a new column named `domain_n`. Make it in a format like "Op_Q1".
```{r personality-unite}
personality_unite <- unite(
data = personality_sep,
col = "domain_n", # new column name
domain, qnumber, # columns to unite
sep = "_Q" # separation characters
) |>
glimpse()
```
### spread() {#spread}
You can reverse the processes above, as well. For example, you can convert data from long format into wide format.
* `key` is the column that contains your new column headers. It is like `names_from` in `pivot_wider()`, but can only take one value (multiple values need to be merged first using `unite()`).
* `value` is the column that contains the values in the new spread columns. It is like `values_from` in `pivot_wider()`.
```{r personality-spread}
personality_spread <- spread(
data = personality_unite,
key = domain_n, # column that contains new headers
value = score # column that contains new values
) |>
glimpse()
```
## Pipes {#pipes}
<div class="small_right"><img src="images/tidyr/pipe_sticker.png" alt="Pipe hex sticker" /></div>
Pipes are a way to order your code in a more readable format.
::: {.info data-latex=""}
Base R recently added a "native pipe" that looks like this: `|>`, while the tidyverse has traditionally used the "magrittr pipe" that looks like this `%>%`. They have a few small differences that you don't need to learn about yet. We'll be using the new native pipe, but you might see the magrittr pipe in materials we haven't updated yet.
:::
Let's say you have a small data table with 10 participant IDs, two columns with variable type A, and 2 columns with variable type B. You want to calculate the mean of the A variables and the mean of the B variables and return a table with 10 rows (1 for each participant) and 3 columns (`id`, `A_mean` and `B_mean`).
One way you could do this is by creating a new object at every step and using that object in the next step. This is pretty clear, but you've created 6 unnecessary data objects in your environment. This can get confusing in very long scripts.
```{r no-pipe-example}
# make a data table with 10 subjects
data_original <- tibble(
id = 1:10,
A1 = rnorm(10, 0),
A2 = rnorm(10, 1),
B1 = rnorm(10, 2),
B2 = rnorm(10, 3)
)
# gather columns A1 to B2 into "variable" and "value" columns
data_gathered <- gather(data_original, variable, value, A1:B2)
# separate the variable column at the _ into "var" and "var_n" columns
data_separated <- separate(data_gathered, variable, c("var", "var_n"), sep = 1)
# group the data by id and var
data_grouped <- group_by(data_separated, id, var)
# calculate the mean value for each id/var
data_summarised <- summarise(data_grouped, mean = mean(value), .groups = "drop")
# spread the mean column into A and B columns
data_spread <- spread(data_summarised, var, mean)
# rename A and B to A_mean and B_mean
data <- rename(data_spread, A_mean = A, B_mean = B)
data
```
::: {.warning data-latex=""}
You *can* name each object `data` and keep replacing the old data object with the new one at each step. This will keep your environment clean, but I don't recommend it because it makes it too easy to accidentally run your code out of order when you are running line-by-line for development or debugging.
:::
One way to avoid extra objects is to nest your functions, literally replacing each data object with the code that generated it in the previous step. This can be fine for very short chains.
```{r ok-chain}
mean_petal_width <- round(mean(iris$Petal.Width), 2)
```
But it gets extremely confusing for long chains:
```{r no-pipe-example-very-bad}
# do not ever do this!!
data <- rename(
spread(
summarise(
group_by(
separate(
gather(
tibble(
id = 1:10,
A1 = rnorm(10, 0),
A2 = rnorm(10, 1),
B1 = rnorm(10, 2),
B2 = rnorm(10,3)),
variable, value, A1:B2),
variable, c("var", "var_n"), sep = 1),
id, var),
mean = mean(value), .groups = "drop"),
var, mean),
A_mean = A, B_mean = B)
```
The pipe lets you "pipe" the result of each function into the next function, allowing you to put your code in a logical order without creating too many extra objects.
```{r pipe-example}
# calculate mean of A and B variables for each participant
data <- tibble(
id = 1:10,
A1 = rnorm(10, 0),
A2 = rnorm(10, 1),
B1 = rnorm(10, 2),
B2 = rnorm(10,3)
) |>
gather(variable, value, A1:B2) |>
separate(variable, c("var", "var_n"), sep=1) |>
group_by(id, var) |>
summarise(mean = mean(value), .groups = "drop") |>
spread(var, mean) |>
rename(A_mean = A, B_mean = B)
```
You can read this code from top to bottom as follows:
1. Make a tibble called `data` with
- id of 1 to 10,
- A1 of 10 random numbers from a normal distribution,
- A2 of 10 random numbers from a normal distribution,
- B1 of 10 random numbers from a normal distribution,
- B2 of 10 random numbers from a normal distribution; and then
2. Gather to create `variable` and `value` column from columns `A_1` to `B_2`; and then
3. Separate the column `variable` into 2 new columns called `var`and `var_n`, separate at character 1; and then
4. Group by columns `id` and `var`; and then
5. Summarise and new column called `mean` as the mean of the `value` column for each group and drop the grouping; and then
6. Spread to make new columns with the key names in `var` and values in `mean`; and then
7. Rename to make columns called `A_mean` (old `A`) and `B_mean` (old `B`)
You can make intermediate objects whenever you need to break up your code because it's getting too complicated or you need to debug something.
::: {.info data-latex=""}
You can debug a pipe by highlighting from the beginning to just before the pipe you want to stop at. Try this by highlighting from `data <-` to the end of the `separate` function and typing cmd-return. What does `data` look like now?
:::
Chain all the steps above using pipes.
```{r personality-pipe}
personality_reshaped <- personality |>
gather("question", "score", Op1:Ex9) |>
separate(question, c("domain", "qnumber"), sep = 2) |>
unite("domain_n", domain, qnumber, sep = "_Q") |>
spread(domain_n, score)
```
## More Complex Example
### Load Data
Get data on infant and maternal mortality rates from the `r pkg("reprores")` package. If you don't have the package, you can download them here:
* [infant mortality](https://psyteachr.github.io/reprores/data/infmort.csv)
* [maternal mortality](https://psyteachr.github.io/reprores/data/matmort.xls)
```{r load-infmort}
data("infmort")
head(infmort)
```
```{r load-matmort}
data("matmort")
head(matmort)
```
### Wide to Long
`matmort` is in wide format, with a separate column for each year. Change it to long format, with a row for each Country/Year observation.
This example is complicated because the column names to gather _are_ numbers. If the column names are non-standard (e.g., have spaces, start with numbers, or have special characters), you can enclose them in backticks (\`) like the example below.
```{r matmort-long}
matmort_long <- matmort |>
pivot_longer(cols = `1990`:`2015`,
names_to = "Year",
values_to = "stats") |>
glimpse()
```
::: {.info data-latex=""}
You can put `matmort` at the first argument to `pivot_longer()`; you don't have to pipe it in. But when I'm working on data processing I often find myself needing to insert or rearrange steps and I constantly introduce errors by forgetting to take the first argument out of a pipe chain, so now I start with the original data table and pipe from there.
:::
Alternatively, you can use the `gather()` function.
```{r matmort-long-gather}
matmort_long <- matmort |>
gather("Year", "stats", `1990`:`2015`) |>
glimpse()
```
### One Piece of Data per Column
The data in the `stats` column is in an unusual format with some sort of confidence interval in brackets and lots of extra spaces. We don't need any of the spaces, so first we'll remove them with `mutate()`, which we'll learn more about in the next lesson.
The `separate` function will separate your data on anything that is not a number or letter, so try it first without specifying the `sep` argument. The `into` argument is a list of the new column names.
```{r matmort-split-separate}
matmort_split <- matmort_long |>
mutate(stats = gsub(" ", "", stats)) |>
separate(stats, c("rate", "ci_low", "ci_hi")) |>
glimpse()
```
::: {.info data-latex=""}
The `gsub(pattern, replacement, x)` function is a
flexible way to do search and replace. The example above replaces all occurances of the `pattern` " " (a space), with the `replacement` "" (nothing), in the string `x` (the `stats` column). Use `sub()` instead if you only want to replace the first occurance of a pattern. We only used a simple pattern here, but you can use more complicated [regex](https://stat.ethz.ch/R-manual/R-devel/library/base/html/regex.html) patterns to replace, for example, all even numbers (e.g., `gsub("[:02468:]", "*", "id = 123456")`) or all occurances of the word colour in US or UK spelling
(e.g., `gsub("colo(u)?r", "***", "replace color, colour, or colours, but not collors")`).
:::
#### Handle spare columns with `extra` {#extra}
::: {.warning data-latex=""}
The previous example should have given you an error warning about
"Additional pieces discarded in 543 rows". This is because `separate` splits the column at the brackets and dashes, so the text `100[90-110]` would split into four values `c("100", "90", "110", "")`, but we only specified 3 new columns. The fourth value is always empty (just the part after the last bracket), so we are happy to drop it, but `separate` generates a warning so you don't do that accidentally. You can turn off the warning by adding the `extra` argument and setting it to "drop". Look at the help for `??tidyr::separate` to see what the other options do.
:::
```{r matmort-split-extra}
matmort_split <- matmort_long |>
mutate(stats = gsub(" ", "", stats)) |>
separate(stats, c("rate", "ci_low", "ci_hi"), extra = "drop") |>
glimpse()
```
#### Set delimiters with `sep` {#sep}
Now do the same with `infmort`. It's already in long format, so you don't need to use `gather`, but the third column has a ridiculously long name, so we can just refer to it by its column number (3).
```{r infmort-split-sep}
infmort_split <- infmort |>
separate(3, c("rate", "ci_low", "ci_hi"), extra = "drop") |>
glimpse()
```
**Wait, that didn't work at all!** It split the column on spaces, brackets, _and_ full stops. We just want to split on the spaces, brackets and dashes. So we need to manually set `sep` to what the delimiters are. Also, once there are more than a few arguments specified for a function, it's easier to read them if you put one argument on each line.
#### {#regex -}
::: {.warning data-latex=""}
You can use [regular expressions](https://stat.ethz.ch/R-manual/R-devel/library/base/html/regex.html)
to separate complex columns. Here, we want to separate on dashes and brackets. You can separate on a list of delimiters by putting them in parentheses, separated by "|". It's a little more complicated because brackets have a special meaning in regex, so you need to "escape" the left one with two backslashes "\\\\".
:::
```{r infmort-split}
infmort_split <- infmort |>
separate(
col = 3,
into = c("rate", "ci_low", "ci_hi"),
extra = "drop",
sep = "(\\[|-|])"
) |>
glimpse()
```
#### Fix data types with `convert` {#convert}
That's better. Notice the _<chr>_ next to `Year`, `rate`, `ci_low` and `ci_hi`. That means these columns hold characters (like words), not numbers or integers. This can cause problems when you try to do thigs like average the numbers (you can't average words), so we can fix it by adding the argument `convert` and setting it to `TRUE`.
```{r infmort-split-convert}
infmort_split <- infmort |>
separate(col = 3,
into = c("rate", "ci_low", "ci_hi"),
extra = "drop",
sep = "(\\[|-|])",
convert = TRUE) |>
glimpse()
```
Do the same for `matmort`.
```{r matmort-split-convert}
matmort_split <- matmort_long |>
mutate(stats = gsub(" ", "", stats)) |>
separate(col = stats,
into = c("rate", "ci_low", "ci_hi"),
extra = "drop",
convert = TRUE) |>
glimpse()
```
### All in one step
We can chain all the steps for `matmort` above together, since we don't need those intermediate data tables.
```{r matmort-pipes}
matmort2 <- matmort |>
gather("Year", "stats", `1990`:`2015`) |>
mutate(stats = gsub(" ", "", stats)) |>
separate(
col = stats,
into = c("rate", "ci_low", "ci_hi"),
extra = "drop",
convert = TRUE
) |>
glimpse()
```
### Columns by Year
Spread out the maternal mortality rate by year.
```{r infmort-wide-spread}
matmort_wide <- matmort2 |>
spread(key = Year, value = rate) |>
print()
```
::: {.warning data-latex=""}
Nope, that didn't work at all, but it's a really common mistake when spreading data. This is because `spread` matches on all the remaining columns, so Afghanistan with `ci_low` of 253 is treated as a different observation than Afghanistan with `ci_low` of 745.
:::
This is where `pivot_wider()` can be very useful. You can set `values_from` to multiple column names and their names will be added to the `names_from` values.
```{r}
matmort_wide <- matmort2 |>
pivot_wider(
names_from = Year,
values_from = c(rate, ci_low, ci_hi)
)
glimpse(matmort_wide)
```
### Experimentum Data
Students in the Institute of Neuroscience and Psychology at the University of Glasgow can use the online experiment builder platform, [Experimentum](https://debruine.github.io/experimentum/). The platform is also [open source on github](https://github.com/debruine/experimentum) for anyone who can install it on a web server. It allows you to group questionnaires and experiments into **projects** with randomisation and counterbalancing. Data for questionnaires and experiments are downloadable in long format, but researchers often need to put them in wide format for analysis.
Look at the help menu for built-in dataset `experimentum_quests` to learn what each column is. Subjects are asked questions about dogs to test the different questionnaire response types.
* current: Do you own a dog? (yes/no)
* past: Have you ever owned a dog? (yes/no)
* name: What is the best name for a dog? (free short text)
* good: How good are dogs? (1=pretty good:7=very good)
* country: What country do borzois come from?
* good_borzoi: How good are borzois? (0=pretty good:100=very good)
* text: Write some text about dogs. (free long text)
* time: What time is it? (time)
To get the dataset into wide format, where each question is in a separate column, use the following code:
```{r}
q <- experimentum_quests |>
pivot_wider(id_cols = session_id:user_age,
names_from = q_name,
values_from = dv) |>
type.convert(as.is = TRUE) |>
print()
```
::: {.info data-latex=""}
The responses in the `dv` column have multiple types (e.g., `r glossary("integer")`, `r glossary("double")`, and `r glossary("character")`), but they are all represented as character strings when they're in the same column. After you spread the data to wide format, each column should be given the ocrrect data type. The function `type.convert()` makes a best guess at what type each new column should be and converts it. The argument `as.is = TRUE` converts columns where none of the numbers have decimal places to integers.
:::
## Glossary {#glossary-tidyr}
`r glossary_table()`
## Further Resources {#resources-tidyr}
* [Tidy Data](http://vita.had.co.nz/papers/tidy-data.html)
* [Chapter 12: Tidy Data](http://r4ds.had.co.nz/tidy-data.html) in *R for Data Science*
* [Chapter 18: Pipes](http://r4ds.had.co.nz/pipes.html) in *R for Data Science*
* [Data wrangling cheat sheet](https://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf)