首页 > 解决方案 > 具有因子的数据帧的复杂计数

问题描述

我有这张桌子。

'data.frame':   5303 obs. of  9 variables:
 $ Metric.ID          : num  7156 7220 7220 7220 7220 ...
 $ Metric.Name        : Factor w/ 99 levels "Avoid accessing data by using the position and length",..: 51 59 59 
 $ Technical.Criterion: Factor w/ 25 levels "Architecture - Multi-Layers and Data Access",..: 4 9 9 9 9 9 9 9 9 9 ...
 $ RT.Snapshot.name   : Factor w/ 1 level "2017_RT12": 1 1 1 1 1 1 1 1 1 1 ...
 $ Violation.status   : Factor w/ 2 levels "Added","Deleted": 2 1 2 2 2 1 1 1 1 1 ...
 $ Critical.Y.N       : num  0 0 0 0 0 0 0 0 0 0 ...
 $ Grouping           : Factor w/ 29 levels "281","Bes",..: 27 6 6 6 6 7 7 7 7 7 ...
 $ Object.type        : Factor w/ 11 levels "Cobol Program",..: 8 7 7 7 7 7 7 7 7 7 ...
 $ Object.name        : Factor w/ 3771 levels "[S:\\SOURCES\\",..: 3771 3770 3769 3768 3767 3    

我想要一个这样的统计输出:对于每个 Technical.Criterion 一行,所有行的总和为 Critical.YN = 0 和 1

在此处输入图像描述

所以我必须将我的数据库的行组合成一个新的矩阵。使用因子总和的值...

但我不知道如何开始......?有什么提示吗?

谢谢

标签: rshiny

解决方案


我相信你要求一个交叉表。因为您没有提供可重现的样本,所以我使用了我的:

xtabs(~ Sub.Category + Category, retail)

产生这个: 在此处输入图像描述

如果您希望根据销售额而不是计数来表示值,那么您可以将代码修改为:

xtabs(Sales ~ Sub.Category + Category, retail)

您将获得以下输出: 在此处输入图像描述

根据 OP 评论中的额外信息进行编辑 如果您想让您的表格也共享一个共同的标题并想要更改该标题的名称,您可以使用names()和的组合dimnames()。Anxtab是一个交叉表,如果你调用dimnames()它,它会返回一个长度为 2 的列表,第一个对应于行,第二个对应于列。

dimnames(xtab(dat))
$Technical.Criterion
[1] "TechnicalCrit1" "TechnicalCrit2" "TechnicalCrit3"

$`Object.type`
[1] "Object.type1" "Object.type2" "Object.type3"

所以给定一个数据框,b

'data.frame':   3 obs. of  9 variables:
 $ Metric.ID          : int  101 102 103
 $ Metric.Name        : Factor w/ 3 levels "A","B","C": 1 2 3
 $ Technical.Criterion: Factor w/ 3 levels "TechnicalCrit1",..: 1 2 3
 $ RT.Snapshot.name   : Factor w/ 3 levels "A","B","C": 1 2 3
 $ Violation.status   : Factor w/ 2 levels "Added","Deleted": 1 2 1
 $ Critical.Y.N       : num  1 0 1
 $ Grouping           : Factor w/ 3 levels "A","B","C": 1 2 3
 $ Object.type        : Factor w/ 3 levels "Object.type1",..: 1 2 3
 $ Object.name        : Factor w/ 3 levels "A","B","C": 1 2 3

我们可以使用xtab然后更改表格顶部的“通用”标题。由于我不知道有多少级别b$Violation.status,我会使用通用的 for 循环:

for(i in 1:length(unique(b$Violation.status))){
  tab[[i]] <- xtabs(Critical.Y.N ~ Technical.Criterion + Object.type, b)
  names(dimnames(tab[[i]]))[2] <- paste("Violation.status", i)
}

这会产生:

                   Violation.status 1
Technical.Criterion Object.type1 Object.type2 Object.type3
     TechnicalCrit1            1            0            0
     TechnicalCrit2            0            0            0
     TechnicalCrit3            0            0            1

我现在可以在我闪亮的应用程序中使用它。


推荐阅读