I have seen some possible discussion of my problem elsewhere but it either wasn't resolved or I could not fully understand if the answer applied, so I'm creating a new question.
The following question in particular touches on this subject but is not resolved. Gathering wide columns into multiple long columns using pivot_longer
Take the following sample data. As you can see there is a unique identifier variable, and then 8 other variables. Of the other 8, you can group them into two sets, gpa and percent_a. For each set there is a class, group, course, and dept value.
In my actual data I have about 20 different sets, all with the same structure, the same four descriptors in each set.
What I would like to do is perform a function similar to pivot_longer. Except instead of combining multiple columns into a set of key and value columns, each unique set in my data (class, group, course, dept) would be grouped into there own key/value columns.
set.seed(101)
df <- data.frame(
id = 1:10,
class_gpa = rnorm(10, 0, 1),
course_gpa = rnorm(10, 0, 1),
group_gpa = rnorm(10, 0, 1),
dept_gpa = rnorm(10, 0, 1),
class_percent_a = rnorm(10, 0, 1),
course_percent_a = rnorm(10, 0, 1),
group_percent_a = rnorm(10, 0, 1),
dept_percent_a = rnorm(10, 0, 1)
)
So in this example, lets say I group all of the gpa values into two columns (gpa_type, and gpa_value) and the percent_a values into two columns (percent_a_type, percent_a_value), then I would end up at the end with only 5 columns:
id, gpa_type, gpa_value, percent_a_type, percent_a_value
Is there a way to do this? Either with pivot_longer or another method. Thanks.