Repeated Measures data set with multiple variables into long format Data set: I have a repeated measures RCT data set with a baseline, post-intervention, and follow-up measurement. There are two variables: x and y, as well as a treatment and subject (id) variable. The treatment took place between baseline and post-intervention. 
Goal: I want to perform a mixed models on response variable X with X_baseline, Y, and treatment as explanatory variables. I will add subject as random effect. 
I want to control for regression to the mean by adding X_baseline as covariate in the model. Hence, I need to have a data frame with the two time points in long format, while retaining the baseline values of x and y. 
Example data set:
set.seed(1)
df <- data.frame(
  subject = 1:10,
  treatment = sample(c("treatment", "placebo"), 10, replace = TRUE),
  x_baseline = sample(1:10),
  x_post_intervention = sample(1:10),
  x_followup = sample(1:10),
  y_baseline = sample(1:10),
  y_post_intervention = sample(1:10),
  y_followup = sample(1:10)
)

My attempt:
df_long <- df %>%
  pivot_longer(
  -c(subject, treatment, x_baseline, y_baseline), 
  names_to = c("time"), 
  values_to = c("x", "y"),
  names_pattern = "(x|y)_(post_intervention|followup)"
)

I appreciate your help.
 A: You needa tweak the regex in names_pattern and pivot wide again:
pivot_longer(df,-c(subject,treatment,x_baseline,y_baseline),
names_to = c("measure", "type"),names_pattern = "([^_]*)_(.*)") %>% 
pivot_wider(names_from="measure",values_from="value")

  subject treatment x_baseline y_baseline type                  x     y
    <int> <fct>          <int>      <int> <chr>             <int> <int>
1       1 treatment          3          4 post_intervention     5    10
2       1 treatment          3          4 followup              1     6
3       2 placebo            1          9 post_intervention     9     7
4       2 placebo            1          9 followup              4     1
5       3 treatment          5          7 post_intervention     1     3
6       3 treatment          5          7 followup              3     3

Something less obscure might be:
fn = function(df,type){
keep = c("subject","treatment","x_baseline","y_baseline")
df = data.frame(df[,c(keep,grep(type,colnames(df),value=TRUE))],type=type)
colnames(df) = gsub(paste0("_",type),"",colnames(df))
df
}

df_long = rbind(fn(df,"post_intervention"),fn(df,"followup"))

head(df_long)
  subject treatment x_baseline y_baseline  x  y              type
1       1 treatment          3          4  5 10 post_intervention
2       2   placebo          1          9  9  7 post_intervention
3       3 treatment          5          7  1  3 post_intervention
4       4 treatment          8          6  6  2 post_intervention
5       5   placebo          2          1 10  6 post_intervention

