列标题包含示例信息我如何将它们分成 R 中的两列

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

我正在尝试将一些数据帧清理成更有用的格式,我是 运行 R studio 1.3.1093 和 R 3.5.3。

我的数据框如下所示:

Peptide 5C_T6m 5C_T12m
PEP 0.5 1.1
TIDE 0.6 1.2

我正在尝试将其转换为:

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

我无法想象如何在两者之间移动。循序渐进。
我是 R 的新手,并且使用 TidyVerse 完成了一些数据重塑,但在我看来这需要多个步骤才能到达那里,而且我很难想象各个步骤。

任何关于我需要采取的步骤或一些代码建议的帮助都会很棒。

谢谢!

函数pivot_longer在这种情况下非常有用

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

根据我的理解,这是一个可能的解决方案。

library(tidyverse)
 
 df <- data.frame(Peptide = c("PEP","TIDE"), C5_T6m = c(0.5,0.6), C5_T12m = c(1.1,1.2)) 
 
 dt <- df %>% 
gather( Timepoint, abundance, 2:3) %>% 
mutate(Temp = str_extract(Timepoint,"5")) %>% 
mutate(Timepoint =  str_extract(Timepoint,"6|12")) %>% 
select(Peptide,Temp,Timepoint,abundance)

结果

>  dt
  Peptide Temp Timepoint abundance
1     PEP    5         6       0.5
2    TIDE    5         6       0.6
3     PEP    5        12       1.1
4    TIDE    5        12       1.2