data.frame(
+ 1:20, sample(70:80, 20, TRUE),
+ sample(70:100, 20, TRUE),
+ sample(70:100, 20, TRUE),
+ sample(170:200, 20, TRUE)
+) |>
+ setNames(c("id", "age", "weight_0", "weight_1", "height_1")) |>
+ wide2long(pattern = c("_0", "_1"), type = "suffix")
+#> id age instance weight height
+#> 1 1 73 0 93 NA
+#> 2 1 NA 1 80 189
+#> 3 2 76 0 71 NA
+#> 4 2 NA 1 78 185
+#> 5 3 73 0 71 NA
+#> 6 3 NA 1 89 196
+#> 7 4 76 0 81 NA
+#> 8 4 NA 1 73 184
+#> 9 5 70 0 98 NA
+#> 10 5 NA 1 85 183
+#> 11 6 70 0 90 NA
+#> 12 6 NA 1 99 183
+#> 13 7 77 0 74 NA
+#> 14 7 NA 1 77 186
+#> 15 8 80 0 81 NA
+#> 16 8 NA 1 72 200
+#> 17 9 72 0 95 NA
+#> 18 9 NA 1 90 173
+#> 19 10 79 0 72 NA
+#> 20 10 NA 1 92 184
+#> 21 11 78 0 90 NA
+#> 22 11 NA 1 90 194
+#> 23 12 72 0 83 NA
+#> 24 12 NA 1 79 194
+#> 25 13 76 0 80 NA
+#> 26 13 NA 1 75 172
+#> 27 14 76 0 100 NA
+#> 28 14 NA 1 76 173
+#> 29 15 74 0 83 NA
+#> 30 15 NA 1 96 181
+#> 31 16 75 0 80 NA
+#> 32 16 NA 1 79 199
+#> 33 17 77 0 71 NA
+#> 34 17 NA 1 95 178
+#> 35 18 76 0 89 NA
+#> 36 18 NA 1 99 175
+#> 37 19 75 0 78 NA
+#> 38 19 NA 1 88 175
+#> 39 20 79 0 83 NA
+#> 40 20 NA 1 98 178
+data.frame(
+ 1:20, sample(70:80, 20, TRUE),
+ sample(70:100, 20, TRUE),
+ sample(70:100, 20, TRUE),
+ sample(170:200, 20, TRUE)
+) |>
+ setNames(c("id", "age", "weight_0", "weight_a_1", "height_b_1")) |>
+ wide2long(pattern = c("_0", "_1"), type = "suffix")
+#> id age instance weight weight_a height_b
+#> 1 1 78 0 74 NA NA
+#> 2 1 NA 1 NA 87 171
+#> 3 2 73 0 78 NA NA
+#> 4 2 NA 1 NA 99 186
+#> 5 3 77 0 71 NA NA
+#> 6 3 NA 1 NA 92 196
+#> 7 4 75 0 80 NA NA
+#> 8 4 NA 1 NA 71 174
+#> 9 5 80 0 71 NA NA
+#> 10 5 NA 1 NA 88 173
+#> 11 6 77 0 74 NA NA
+#> 12 6 NA 1 NA 79 195
+#> 13 7 72 0 90 NA NA
+#> 14 7 NA 1 NA 86 200
+#> 15 8 76 0 93 NA NA
+#> 16 8 NA 1 NA 99 175
+#> 17 9 79 0 99 NA NA
+#> 18 9 NA 1 NA 95 192
+#> 19 10 79 0 81 NA NA
+#> 20 10 NA 1 NA 97 179
+#> 21 11 76 0 81 NA NA
+#> 22 11 NA 1 NA 74 175
+#> 23 12 75 0 90 NA NA
+#> 24 12 NA 1 NA 93 186
+#> 25 13 77 0 94 NA NA
+#> 26 13 NA 1 NA 71 179
+#> 27 14 79 0 76 NA NA
+#> 28 14 NA 1 NA 92 200
+#> 29 15 76 0 99 NA NA
+#> 30 15 NA 1 NA 96 184
+#> 31 16 72 0 78 NA NA
+#> 32 16 NA 1 NA 92 196
+#> 33 17 73 0 84 NA NA
+#> 34 17 NA 1 NA 80 180
+#> 35 18 76 0 75 NA NA
+#> 36 18 NA 1 NA 95 199
+#> 37 19 77 0 84 NA NA
+#> 38 19 NA 1 NA 79 170
+#> 39 20 80 0 93 NA NA
+#> 40 20 NA 1 NA 97 190
+# Optional filling of missing values by last observation carried forward
+# Needed for mmrm analyses
+long_missings |>
+ # Fills record ID assuming none are missing
+ tidyr::fill(record_id) |>
+ # Grouping by ID for the last step
+ dplyr::group_by(record_id) |>
+ # Filling missing data by ID
+ tidyr::fill(names(long_missings)[!names(long_missings) %in% new_names]) |>
+ # Remove grouping
+ dplyr::ungroup()
+#> Error: object 'long_missings' not found
+