Reshape multiple value columns to wide format

前端 未结 5 519
难免孤独
难免孤独 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 12:07

    I prefer the tabulate function in package tables for this. It requires factors, but this is anyway a good idea with the type of data you have.

    library(tables)
    expensesByMonth$month= as.factor(expensesByMonth$month)
    expensesByMonth$expense_type= as.factor(expensesByMonth$expense_type)
    tabular(expense_type~(month)*(value+percent)*(sum),data=expensesByMonth)
    # Optional formatting
    tabular(expense_type~month*
       ((Format(digits=1))*value+(Format(digits=3))*percent)*sum,
       data=expensesByMonth)
    

    Partial output:

                           value      percent  value      percent  value      percent 
    expense_type           sum        sum      sum        sum      sum        sum     
    Adjustment              442       0.124025    2       0.000506   16       0.003573
    Bank Service Charge     200       0.056073  200       0.050646  200       0.043650
    Cable                    21       0.005980   36       0.009200    0       0.000000
    

提交回复
热议问题