Need: Pivot from wide to long, stacking groups of corresponding columns.
In essence, I have 3 sets of 5 columns with a need for each of the corresponding columns to be stacked into 1 (i.e., the first variable in each of the 3 sets becomes 1 column, the second variable in each each is the 2nd column, etc). For instance, I need: columns #2, 7, & 12 to all be in 1 column, 3, 8, & 13 in the next column, ... 6, 11, & 16 all in 1 column.
Data structure: I have a dataset that resembles this:
df <- tibble(
pid = c(1, 2, 3, 4),
v1_1 = c(19, NA, NA, NA),
v1_2 = c(12, NA, NA, NA),
v2_1 = c(15, NA, NA, NA),
v2_2 = c(19, NA, NA, NA),
v1_entry_3 = c(11, NA, NA, NA),
v1_1_1 = c(NA, NA, 36, NA),
v1_2_1 = c(NA, NA, 35, NA),
v2_1_1 = c(NA, NA, 31, NA),
v2_2_1 = c(NA, NA, 39, NA),
v1_entry_3_1 = c(NA, NA, 33, NA),
v1_1_2 = c(NA, 26, NA, 41),
v1_2_2 = c(NA, 29, NA, 44),
v2_1_2 = c(NA, 21, NA, 42),
v2_2_2 = c(NA, 20, NA, 45),
v1_entry_3_2 = c(NA, 22, NA, 44),
age = c(19, 21, 33, 47)
)
In the end, I need data that look like this:
df_t <- tibble(
pid = c(1, 2, 3, 4),
v1_1 = c(19, 26, 36, 41),
v1_2 = c(12, 29, 35, 44),
v2_1 = c(15, 21, 31, 42),
v2_2 = c(19, 20, 39, 45),
v1_entry_3 = c(11, 22, 33, 44),
age = c(19, 21, 33, 47)
)