重塑不整洁的数据框,将行扩展为列名

时间:2020-07-27 04:48:25

标签: r reshape2

已经搜索了线程,但不了解可以解决我所拥有的数据帧问题的解决方案。

我当前的数据帧(df):

# A tibble: 8 x 29
  `Athlete`       Monday...2 Tuesday...3 Wednesday...4 Thursday...5 Friday...6 Saturday...7 Sunday...8
  <chr>           <chr>      <chr>       <chr>         <chr>        <chr>      <chr>        <chr>     
1 Date            29/06/2020 30/06/2020  43837.0       43868.0      43897.0    43928.0      43958.0   
2 HR              47.0       54.0        51.0          56.0         59.0       NA           NA        
3 HRV             171.0      91.0        127.0         99.0         77.0       NA           NA        
4 Sleep Duration  9.11       7.12        8.59          7.15         8.32       NA           NA        
5 Sleep Efficien~ 92.0       94.0        89.0          90.0         90.0       NA           NA        
6 Recovery Score  98.0       66.0        96.0          72.0         46.0       NA           NA        
7 Life Stress     NO         NO          NO            NO           NO         NA           NA        
8 Sick            NO         NO          NO            NO           NO         NA           NA

已经尝试使用传播和更广泛地旋转,但我知道为了获得所需的输出,需要附加功能,这超出了我对R的理解。

我需要吗

所需的输出:

 Date        HR       HRV      Sleep Duration   Sleep Efficiency   Recovery Score   Life Stress  Sick 
   29/06/2020    47.0      171.0       9.11
    30/06/2020   54.0      91.0        7.12
    43837.0      51.0      127.0       8.59
    43868.0      56.0      99.0        7.15
    43897.0      59.0      77.0        8.32
    43928.0       NA       NA           NA
    43958.0       NA       NA           NA

谢谢

1 个答案:

答案 0 :(得分:0)

在Base R中,您将执行以下操作:

type.convert(setNames(data.frame(t(df[-1]), row.names = NULL), df[,1]))

        Date HR HRV Sleep Duration Sleep Efficien~ Recovery Score Life Stress Sick
1 29/06/2020 47 171           9.11              92             98          NO   NO
2 30/06/2020 54  91           7.12              94             66          NO   NO
3    43837.0 51 127           8.59              89             96          NO   NO
4    43868.0 56  99           7.15              90             72          NO   NO
5    43897.0 59  77           8.32              90             46          NO   NO
6      43928 NA  NA             NA              NA             NA        <NA> <NA>
7      43958 NA  NA             NA              NA             NA        <NA> <NA>