Search code examples
rsubstringconcatenationreshape

reshape, concatenate and create new column from horizontal to verical dataframe


I have large dataset with some of it shown here

data<-read.table(text="SR_ID   GCS_pre_desc    EDA_pre_desc    GCS_post_desc   EDA_post_desc   HR_pre  SBP_pre DBP_pre HR_post SBP_post    DBP_post
1.00    5.800   5.240   1.400   5.500   88  127 57  83  143 83
2.00    3.300   5.580   5.300   6.020   57  153 63  69  108 51
3.00    1.300   5.700   3.700   7.100   77  121 64  81  98  44
4.00    10.400  3.370   9.000   3.030   54  121 39  69  145 65", sep="", header=T)

I want to reshape my data to

  1. put identical column headings below each other eg HR_post below HR_pre
  2. Create new column Pre vs. post
  3. Concatenate column heading eg HR_pre vs.post (as shown in the screenshot below).

Any advice will be greatly appreciated.

enter image description here


Solution

  • We can use pivot_longer from tidyr

    library(dplyr)
    library(tidyr)
    data %>% 
       pivot_longer(cols = -SR_ID, names_to = c(".value", "prevspost"), 
               names_pattern = "(.*)_(pre|post.*)")