繁体   English   中英

R中的三向制表

[英]3-way tabulation in R

我有一个看起来像的数据集

| ID | Category | Failure |
|----+----------+---------|
|  1 | a        | 0       |
|  1 | b        | 0       |
|  1 | b        | 0       |
|  1 | a        | 0       |
|  1 | c        | 0       |
|  1 | d        | 0       |
|  1 | c        | 0       |
|  1 | failure  | 1       |
|  2 | c        | 0       |
|  2 | d        | 0       |
|  2 | d        | 0       |
|  2 | b        | 0       |

这是数据,其中每个ID通过事件{a, b, c, d}的中间序列可能以失败事件结束。 我希望能够计算每个中间事件因故障事件而发生的ID数。

所以,我想要一张表格

|            | a | b | c | d |
|------------+---+---+---+---|
| Failure    | 4 | 5 | 6 | 2 |
| No failure | 9 | 8 | 6 | 9 |

其中,例如,数字4表示发生故障的ID中a 4个在ID中以失败结束。

我将如何在R中执行此操作?

您可以使用table为例:

dat <- data.frame(categ=sample(letters[1:4],20,rep=T),
                  failure=sample(c(0,1),20,rep=T))

res <- table(dat$failure,dat$categ)
rownames(res) <- c('Failure','No failure')
res
           a b c d
Failure    3 2 2 1
No failure 1 2 4 5

您可以使用barplotbarplot

barplot(res)

在此处输入图片说明

编辑通过ID得到这个,你可以使用by例如:

  dat <- data.frame(ID=c(rep(1,9),rep(2,11)),categ=sample(letters[1:4],20,rep=T),
               failure=sample(c(0,1),20,rep=T))
 by(dat,dat$ID,function(x)table(x$failure,x$categ))
dat$ID: 1

    a b c d
  0 1 2 1 3
  1 1 1 0 0
--------------------------------------------------------------------------------------- 
dat$ID: 2

    a b c d
  0 1 2 3 0
  1 1 3 1 0

使用Tapply 编辑

另一种方法是使用tapply

  with(dat,tapply(categ,list(failure,categ,ID),length))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM