library(tidyverse)
- Read in the
ChickWeight
dataset. This data is from an
experiment on the effect of diet on early growth of chicks. Call it
chicks
.
chicks <- datasets::ChickWeight
- Reshape to wide format using
pivot_wider
. Use the
arguments names_from = Time
and
values_from = weight
. Call the new data
chicks_wide
.
chicks_wide <- chicks %>% pivot_wider(names_from = Time, values_from = weight)
chicks_wide
# A tibble: 50 × 14
Chick Diet `0` `2` `4` `6` `8` `10` `12` `14` `16` `18` `20` `21`
<ord> <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 1 42 51 59 64 76 93 106 125 149 171 199 205
2 2 1 40 49 58 72 84 103 122 138 162 187 209 215
3 3 1 43 39 55 67 84 99 115 138 163 187 198 202
4 4 1 42 49 56 67 74 87 102 108 136 154 160 157
5 5 1 41 42 48 60 79 106 141 164 197 199 220 223
6 6 1 41 49 59 74 97 124 141 148 155 160 160 157
7 7 1 41 49 57 71 89 112 146 174 218 250 288 305
8 8 1 42 50 61 71 84 93 110 116 126 134 125 NA
9 9 1 42 51 59 68 85 96 90 92 93 100 100 98
10 10 1 41 44 52 63 74 81 89 96 101 112 120 124
# ℹ 40 more rows
- Filter the data so that time
0
is <= 40 and time
21
>= 200. Reassign to chicks_wide
.
chicks_wide <- chicks_wide %>% filter(`0` <= 40 & `21` >= 200)
chicks_wide
# A tibble: 9 × 14
Chick Diet `0` `2` `4` `6` `8` `10` `12` `14` `16` `18` `20` `21`
<ord> <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2 1 40 49 58 72 84 103 122 138 162 187 209 215
2 21 2 40 50 62 86 125 163 217 240 275 307 318 331
3 25 2 40 49 62 78 102 124 146 164 197 231 259 265
4 28 2 39 46 58 73 92 114 145 156 184 207 212 233
5 29 2 39 48 59 74 87 106 134 150 187 230 279 309
6 36 3 39 48 61 76 98 116 145 166 198 227 225 220
7 46 4 40 52 62 82 101 120 144 156 173 210 231 238
8 48 4 39 50 62 80 104 125 154 170 222 261 303 322
9 49 4 40 53 64 85 108 128 152 166 184 203 233 237
- Select columns Chick, Diet,
0
, and 21
.
Reassign to chicks_wide
.
chicks_wide <- chicks_wide %>% select(Chick, Diet, `0`, `21`)
chicks_wide
# A tibble: 9 × 4
Chick Diet `0` `21`
<ord> <fct> <dbl> <dbl>
1 2 1 40 215
2 21 2 40 331
3 25 2 40 265
4 28 2 39 233
5 29 2 39 309
6 36 3 39 220
7 46 4 40 238
8 48 4 39 322
9 49 4 40 237
- Reshape to long format using
pivot_longer
. Pivot the
numeric columns. Use the arguments names_to =
and
values_to =
. Call the data chicks_long
.
chicks_wide %>% pivot_longer(c(`0`, `21`), names_to = "Time", values_to = "weight")
# A tibble: 18 × 4
Chick Diet Time weight
<ord> <fct> <chr> <dbl>
1 2 1 0 40
2 2 1 21 215
3 21 2 0 40
4 21 2 21 331
5 25 2 0 40
6 25 2 21 265
7 28 2 0 39
8 28 2 21 233
9 29 2 0 39
10 29 2 21 309
11 36 3 0 39
12 36 3 21 220
13 46 4 0 40
14 46 4 21 238
15 48 4 0 39
16 48 4 21 322
17 49 4 0 40
18 49 4 21 237