Reshape multiple value columns to wide format

前端 未结 5 455
难免孤独
难免孤独 2020-11-22 11:32

I have the following data frame and i want to use cast to create a \"pivot table\" with columns for two values (value and percent). Here is the data frame:

         


        
5条回答
  •  忘了有多久
    2020-11-22 11:59

    Your best option is to reshape your data to long format, using melt, and then to dcast:

    library(reshape2)
    
    meltExpensesByMonth <- melt(expensesByMonth, id.vars=1:2)
    dcast(meltExpensesByMonth, expense_type ~ month + variable, fun.aggregate = sum)
    

    The first few lines of output:

                 expense_type 2012-02-01_value 2012-02-01_percent 2012-03-01_value 2012-03-01_percent
    1              Adjustment           442.37        0.124025031             2.00       0.0005064625
    2     Bank Service Charge           200.00        0.056072985           200.00       0.0506462461
    3                   Cable            21.33        0.005980184            36.33       0.0091998906
    4                 Charity             0.00        0.000000000             0.00       0.0000000000
    

提交回复
热议问题