Search code examples
rreshape

Unpivot multiple group columns in R


I have a data frame which I want unpivot based on group using R. My input is like Input dataframe


userid=c(1,2,3)
GroupA_measure1=c(65,96,12)
GroupA_measure2=c(70,89,14)
GroupB_measure1=c(45,12,38)
GroupB_measure2=c(50,8,40)

Input=data.frame(userid,GroupA_measure1,GroupA_measure2,GroupB_measure1,GroupB_measure2)

userid=c(1,1,2,2,3,3)
measure=c(1,2,1,2,1,2)
GroupA=c(65,70,96,89,12,14)
GroupB=c(45,50,12,8,38,40)

Output=data.frame(userid,measure,GroupA,GroupB)

My expected output is like Output data frame. Please help me out if you have the solution for this


Solution

  • You can do:

    library(tidyverse)
    Input %>%
      pivot_longer(-userid,
                   names_pattern = '(.*)_measure(.)',
                   names_to = c('.value', 'measure'))
    
    # A tibble: 6 x 4
      userid measure GroupA GroupB
       <dbl> <chr>    <dbl>  <dbl>
    1      1 1           65     45
    2      1 2           70     50
    3      2 1           96     12
    4      2 2           89      8
    5      3 1           12     38
    6      3 2           14     40