是否有 R 函数可以让我使用模式匹配拆分和重组数据框?

Is there an R function that lets me split and reorganize a data frame using pattern matching?

我有一个如下所示的数据框:

Subject_ID| Burn_L |Burn_R |
1         |  23    | 17    |
2         |  5     | 28    |

我需要数据框采用这种结构

Subject_ID| Side   |Burn_Radius|
1         | L_Side | 23
1         | R_Side | 17
2         | L_Side | 5
2         | R_side | 28

我尝试使用 Tidyverse gather(),但它不能完全按照我的需要工作。有人知道我转换这些数据的方法吗?

这是你需要的吗?值的名称似乎从您的输入更改为输出,所以我不太确定。

> dat %>% tidyr::pivot_longer(-Subject_ID, names_to="Side", values_to="Burn_Radius")
# A tibble: 4 x 3
  Subject_ID Side   Burn_Radius
       <int> <chr>        <int>
1          1 Burn_L          23
2          1 Burn_R          17
3          2 Burn_L           5
4          2 Burn_R          28

这个有用吗:

library(dplyr)
library(tidyr)
df %>% rename( 'L_Side' = Burn_L,'R_Side' =  Burn_R) %>% 
     pivot_longer(-Subject_ID, names_to = 'Side', values_to = 'Burn_Radius')
# A tibble: 4 x 3
  Subject_ID Side   Burn_Radius
       <int> <chr>        <dbl>
1          1 L_Side          23
2          1 R_Side          17
3          2 L_Side           5
4          2 R_Side          28