How would I transform the following data.frame from wide to long while also generating a group column? Example data: dat <- data.frame(ID=paste0("id",1:10),readout1_g1=rnorm(10),readout1_g2=rnorm(10),readout1_g3=rnorm(10),readout2_g1=rnorm(10),readout2_g2=rnorm(10),readout2_g3=rnorm(10)) I have the following groups I am interested in that are part of the column names groups <- c("g1","g2","g3","g1","g2","g3") dat ID readout1_g1 readout1_g2 readout1_g3 readout2_g1 readout2_g2 readout2_g3 1 id1 0.2732715 -0.6328317 -1.3024276 1.7248944… Read More Wide to Long preserving a group