I would to reverse the reshaping from wide back to long format but am stack how I should proceed so that the values for a1_* be placed in a1. Is there a workaround this?
library(tidyverse)
df <- tibble(
id = c("s001", "s002", "s002", "s003", "s003",
"s004", "s005"),
a1 = c("A", "B", "C", "A", "D", "A", "B"),
a2 = c(23, 24, 45, 23, 56, 45, 34),
a3 = c("Primary", "Secondary", "Tertiary", "Primary",
"Tertiary", "Secondary", "Primary"))
#---- Reshape long to wide
df <- df %>%
group_by(id) %>%
mutate(index = row_number()) %>% ungroup()
df_wide <- df %>%
pivot_wider(id_cols = id,
names_from = index,
values_from = starts_with("a"))
#---- Reverse back
df_long <- df_wide %>%
pivot_longer(!id,
names_to = "index",
names_prefix = "a\\d_"
)