Just posting another solution @spunky
If you're working in the tidyverse, tidyr has some relatively recent developments to help with these tasks, namely through pivot_wider, pivot_longer:
# data
x <- rnorm(100)
g1 <- rep(1:5, each=20)
id <- rep(1:20, times=5)
df <- data.frame(x,id,g1)
#...