rearranging a data.frame using pivot_wider

hello,
i am trying to rearrange a data frame that looks like this (but with more columns and sample names):

Sample Point Tretment Milking hour Fatty_acid_1
1 Start High 17:00 1035.645922
1 Start High 2:30 684.861581
1 End High 17:00 822.0507663
1 End High 2:30 1129.390873
2 Start High 17:00 913.394653
2 Start High 2:30 1115.686339
2 End High 17:00 762.1805403
2 End High 2:30 639.023931

into this:

Fatty_acid_1 Point Tretment Milking hour Sample 1 Sample 2
Fatty_acid_1 Start High 17:00 1035.6 913.4
Fatty_acid_1 Start High 2:30 684.9 1115.7
Fatty_acid_1 End High 17:00 822.1 762.2
Fatty_acid_1 End High 2:30 1129.4 639.0

I've tried to use pivot_wider:

Blockquote

Group_MF %>% pivot_longer(cols = 5:6, names_to =Group_MF$Sample,names_sep)

but i get this:

Sample Milking Point Tretment Sample1._93 Sample1_335 Sample2_93 Sample2_335
1 0.708333333 Start High 1035.6 913.4 270.9 246.2
2 0.104166667 Start High 684.9 1115.7 163.8 343.1
3 0.708333333 End High 822.1 762.2 246 35.7
4 0.104166667 End High 1129.4 639 316.8 320.3

Hi Mat,
you said that you've tried pivot_wider(), but in fact, your code uses pivot_longer(). I think you want to use pivot_wider() here and then it should work without problems.

This one worked well for me:
pivot_wider(Group_MF, names_from = Sample, names_prefix = "Sample_", values_from = Fatty_acid_1)
which gives you

Point Tretment Milking.hour Sample_1 Sample_2
Start High 17:00 1035.6459 913.3947
Start High 02:30 684.8616 1115.6863
End High 17:00 822.0508 762.1805
End High 02:30 1129.3909 639.0239
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.