html – R:输出带小计的类似枢轴的表

我正在尝试在R中进行交叉制表,并使其输出尽可能地类似于我在Excel数据透视表中获得的内容.目标是用Excel和Word自动替换用Excel和Word手动生成的报告;已经处理了数据争论和图表,但缺少一些表格.所以,鉴于此代码:

set.seed(2)
df<-data.frame("ministry"=paste("ministry ",sample(1:3,20,replace=T)),"department"=paste("department ",sample(1:3,20,replace=T)),"program"=paste("program ",sample(letters[1:20],20,replace=F)),"budget"=runif(20)*1e6)
library(tables)
library(dplyr)
arrange(df,ministry,department,program)
tabular(ministry*department~((Count=budget)+(Avg=(mean*budget))+(Total=(sum*budget))),data=df)

产量(实际数据要复杂得多):

                                 Avg    Total  
 ministry    department    Count budget budget 
 ministry  1 department  1 5     479871 2399356
             department  2 1     770028  770028
             department  3 1     184673  184673
 ministry  2 department  1 2     170818  341637
             department  2 1     183373  183373
             department  3 3     415480 1246440
 ministry  3 department  1 0        NaN       0
             department  2 5     680102 3400509
             department  3 2     165118  330235

这与Excel结果一样接近.我需要显示小计,就像这样(使用完全相同的数据在Excel中生成):

是否有可能在R中得到这样的东西(没有手动编码逐个单元格的表格)?

谢谢!

最佳答案 将左侧更换为:

ministry * (department + 1) + 1

也就是说,试试这个:

tabular(ministry * (department + 1) + 1 ~
           ((Count = budget) + (Avg = (mean * budget)) + (Total = (sum * budget))), 
        data = df)

赠送:

                                 Avg    Total  
 ministry    department    Count budget budget 
 ministry  1 department  1  5    479871 2399356
             department  2  1    770028  770028
             department  3  1    184673  184673
             All            7    479151 3354057
 ministry  2 department  1  2    170818  341637
             department  2  1    183373  183373
             department  3  3    415480 1246440
             All            6    295242 1771449
 ministry  3 department  1  0       NaN       0
             department  2  5    680102 3400509
             department  3  2    165118  330235
             All            7    532963 3730744
             All           20    442813 8856250

更新:更正.

点赞