I've got a dataset that looks like this:
df_start <- tribble(
~name, ~age, ~x1_sn_ctrl1, ~x1_listing2_2, ~x1_affect1, ~x2_sn_ctrl1, ~x1_listing2_2, ~x2_affect1, ~number,
"John", 28, 1, 1, 9, 4, 5, 9, 6,
"Paul", 27, 2, 1, 4, 1, 3, 3, 4,
"Ringo", 31, 3, 1, 2, 2, 5, 8, 9)
I need to pivot_longer()
while handling the groupings within my columns:
- There are 2 x-values (1 and 2)
- There are 3 questions (sn_ctrl1, listing2_2, affect1) for each x-value
In my actual dataset, there are 14 x's.
Essentially, what I'd like to do is to apply pivot_longer()
to the x-values but leave my 3 questions (sn_ctrl1, listing2_2, affect1) wide.
What I'd like to end up with is this:
df_end <- tribble(
~name, ~age, ~xval, ~sn_ctrl1, ~listing2_2, ~affect1, ~number,
"John", 28, 1, 1, 1, 9, 6,
"John", 28, 2, 4, 5, 9, 6,
"Paul", 27, 1, 2, 1, 4, 4,
"Paul", 27, 2, 1, 3, 3, 4,
"Ringo", 31, 1, 3, 1, 2, 9,
"Ringo", 31, 2, 2, 5, 8, 9)
I have tried lots of very unsuccessful attempts playing with regex in names_pattern
& pivot_longer
but am completely striking out.
Anyone know how to tackle this?
THANKS!
PS: Note that I tried to make a straightforward reproducible example. The actual names of my columns vary slightly. For instance, there is x1_sn_ctrl1
& x1_attr1_ctrl2
.