在R中具有n> 2个类别的交叉列表:隐藏具有零个案例的行

时间:2015-05-13 19:48:42

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

我正在尝试在R中进行交叉制表,并使其输出尽可能地与Excel数据透视表中的内容相似。所以,鉴于此代码:

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    <---- LOOK HERE
             department  2 5     680102 3400509
             department  3 2     165118  330235

如何让输出隐藏零频率的行? 我正在使用tables::tabular,但任何其他包对我都有好处(只要有一种方法,甚至是间接输出到html)。 这是用于使用R Markdown生成HTML或Latex并使用我的脚本的结果显示表格,或者像上面的示例一样在数据透视表中显示表格。但没有多余的一行。

谢谢!

2 个答案:

答案 0 :(得分:0)

为什么不直接使用dplyr?

df %>%
group_by(ministry, department) %>%
summarise(count = n(),
        avg_budget = mean(budget, na.rm = TRUE),
        tot_budget = sum(budget, na.rm = TRUE))



     ministry    department count avg_budget tot_budget
1 ministry  1 department  1     5   479871.1  2399355.6
2 ministry  1 department  2     1   770027.9   770027.9
3 ministry  1 department  3     1   184673.5   184673.5
4 ministry  2 department  1     2   170818.3   341636.5
5 ministry  2 department  2     1   183373.2   183373.2
6 ministry  2 department  3     3   415479.9  1246439.7
7 ministry  3 department  2     5   680101.8  3400508.8
8 ministry  3 department  3     2   165117.6   330235.3

答案 1 :(得分:0)

虽然我根本不了解tabular对象是如何制作的(因为它说它是一个列表但似乎表现得像数据框),你可以像往常一样选择单元格,所以

> results <-tabular(ministry*department~((Count=budget)+(Avg=(mean*budget))+(Total=(sum*budget))),data=df)
> results[results[,1]!=0,]

                                 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  2 5     680102 3400509
             department  3 2     165118  330235

这就是解决方案。

我刚刚找到解决方案,感谢此用户对其他问题的回复https://stackoverflow.com/users/516548/g-grothendieck