R:输出一个类似枢轴的 table 和小计

R: output a pivot-like table with subtotals

我正在尝试在 R 中制作交叉表,并使其输出尽可能类似于我在 Excel 数据透视表 table 中得到的结果。 objective 是用 Excel 替换手动生成的报告,用 R Markdown 自动生成的 Word 替换;数据整理和图表已经处理完毕,但缺少一些 table。因此,给定此代码:

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 中得到类似的东西(无需手动对 table 逐个单元格进行编码)?

谢谢!

将左侧替换为:

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

更新:更正。