Search code examples
rdataframedatatablepivotexpand

Expand an R Column Values To Column Headers with Another Column's values


I'm trying to expand an R data table that looks like this:

a   step_num   duration 

1          1          5 
1          2          4
1          3          1
2          1          7
2          2          2
2          3          9
3          1          1
3          2          1
3          3          3

Into something that looks like this:

a | step_num | duration | 1_duration | 2_duration | 3_duration |
----------------------------------------------------------------
1          1          5            5           -            -
1          2          4            -           4            -
1          3          1            -           -            1
2          1          7            7           -            -
2          2          2            -           2            -
2          3          9            -           -            9
3          1          1            1           -            -
3          2          1            -           1            -
3          3          3            -           -            3

I'm wondering if there's an 'expand' function, so to speak, that would do this.

Thanks!


Solution

  • We can do this in base r.

    cbind(df,
          reshape(df, idvar = c("a","step_num"), timevar = "step_num", direction = "wide")[,-1])
    
    #>   a step_num duration duration.1 duration.2 duration.3
    #> 1 1        1        5          5         NA         NA
    #> 2 1        2        4         NA          4         NA
    #> 3 1        3        1         NA         NA          1
    #> 4 2        1        7          7         NA         NA
    #> 5 2        2        2         NA          2         NA
    #> 6 2        3        9         NA         NA          9
    #> 7 3        1        1          1         NA         NA
    #> 8 3        2        1         NA          1         NA
    #> 9 3        3        3         NA         NA          3
    

    Created on 2019-05-21 by the reprex package (v0.2.1)