【问题标题】:R: output a pivot-like table with subtotalsR:输出一个带有小计的类似数据透视表
【发布时间】:2015-05-14 14:18:23
【问题描述】:

我正在尝试在 R 中制作一个交叉制表,并使其输出尽可能类似于我在 Excel 数据透视表中得到的内容。目标是将使用 Excel 和 Word 手动制作的报告替换为使用 R Markdown 自动制作的报告;数据整理和图表已经处理好,但缺少一些表格。所以,给定这段代码:

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

谢谢!

【问题讨论】:

  • 实际上在某些时候出于某种原因我更改了种子编号,它与屏幕截图中的数据不完全相同,但它根本不会影响问题。 ¯_(ツ)_/¯

标签: html r pivot-table r-markdown xtable


【解决方案1】:

将左侧替换为:

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

更新:更正。

【讨论】:

  • 不敢相信这么简单,谢谢!。你也知道如何隐藏 NaN 行吗? (部 3 部门 1)
  • (他们真的需要处理小插曲,它们对我们 R 的初学者一点帮助都没有。)
  • 如果tab 是上面显示的结果,那么tab[,2] &lt;- lapply(tab[,2], function(x) if (is.nan(x)) 0 else x) 会将NaN 替换为0
  • 我一直在寻找tab[tab[,1]!=0,](隐藏频率为零的行),但是谢谢,我从您的示例中学会了这样做! (虽然我还是不明白这个对象。)
  • @s_a 仍然比 proc tabulate 容易:}
猜你喜欢
  • 2018-05-31
  • 2011-10-03
  • 2018-09-27
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多