Search code examples
rtidyversetidyrdata-cleaning

Column titles contain sample info how do i split them into two columns in R


I am trying to clean up some data frames to a more useful format, I am running R studio 1.3.1093 and R 3.5.3.

My data frame looks like this:

Peptide 5C_T6m 5C_T12m
PEP 0.5 1.1
TIDE 0.6 1.2

and I am trying to convert it to:

Peptide Temp Timepoint abundance
PEP 5 6 0.5
TIDE 5 6 0.6
PEP 5 12 1.1
TIDE 5 12 1.2

I can't visualize in my head how it is possible to move between the two. in a stepwise approach.
Im new to R, and have done some bits of data reshaping using TidyVerse, but this seems to me like it requires multiple steps to get there, and its is hard for me to visualise the individual steps.

Any help with either just the steps i would need to take or some code suggestions would be great.

Thanks!


Solution

  • The function pivot_longer is very useful in this kind of cases

    df %>%  pivot_longer(cols=!Peptide, 
                     names_to = c("Temp", "Timepoint"),
                     names_pattern = "(.*)C_T(.*)m",
                     values_to = "abundance")