Search code examples
rreshape2

Reshape long to wide efficiently with amount variable and several ID variables


I have data resembling a much, much larger version of the first chart below. I would like to "unmelt" it into the second chart, but I cannot do it efficiently. At the bottom, I have my most recent attempt where IDVars is the first three columns below, essentially. It ran for 15 minutes before I needed to kill it.

Name ID Trial Variable Amount
Name 1 1 1 FinalSalary 300.00
Name 1 1 1 FinalDCBalance 400.00
Name 1 1 2 FinalSalary 300.00
Name 1 1 2 FinalDCBalance 300.00
Name 2 2 1 FinalSalary 400.00
Name 2 2 1 FinalDCBalance 400.00
Name 2 2 2 FinalSalary 200.00
Name 2 2 2 FinalDCBalance 300.00
Name 3 3 1 FinalSalary 100.00
Name 3 3 2 FinalDCBalance 400.00
Name ID Trial FinalSalary FinalDCBalance
Name 1 1 1 300 400
Name 1 1 2 300 300
Name 2 2 1 400 400
Name 2 2 2 200 300
Name 3 3 1 100 400
Name 3 3 2 300 100
unmelt <- reshape(dataframe, idvar = IDVars, v.names = 'variable', direction = 'wide', timevar = 'Amount')

Solution

  • We can use pivot_wider

    library(tidyr)
    pivot_wider(df1, names_from = 'Variable', values_from = 'Amount')