Search code examples
rreshapetranspose

how to transpose a dataset from wide format to long format in R


The dataset is similar to the following:

ID SEX bloodpressure1 bloodpressure2 bloodpressure3 weight1 weight2 weight3
1   1     90              100           NA            100     105     112
2   0      101            120          115            140     NA     150

*There are over 200 variables

I want the output to be as following:

ID SEX n bloodpressure weight
1   1  1      90        100
1   1  2      100       105
1   1  3      NA        112
2   0  1      101       140
2   0  2      120       NA
2   0  3      115       150

I tried solutions offered in this link: Using Reshape from wide to long in R but since the variable names in my dataset does not have '_' between the letter and the number, I don't how to separate the column name to make it work.

Thank you in advance for any help!


Solution

  • Using tidyr::pivot_longer :

    tidyr::pivot_longer(df, cols = -c(ID, SEX), 
                       names_to = c('.value', 'n'), 
                       names_pattern = '(.*)(\\d+)')
    
    # A tibble: 6 x 5
    #     ID   SEX n     bloodpressure weight
    #  <int> <int> <chr>         <int>  <int>
    #1     1     1 1                90    100
    #2     1     1 2               100    105
    #3     1     1 3                NA    112
    #4     2     0 1               101    140
    #5     2     0 2               120     NA
    #6     2     0 3               115    150