如何获得R中3变量表的行百分比?

时间:2015-02-16 01:53:15

标签: r

我有以下代码:

> library(MASS)
> with(bacteria, table(trt, y, week))
, , week = 0

         y
trt        n  y
  placebo  2 19
  drug     2 12
  drug+    1 14

, , week = 2

         y
trt        n  y
  placebo  1 19
  drug     2 11
  drug+    1 10

, , week = 4

         y
trt        n  y
  placebo  4 14
  drug     5  7
  drug+    2 10

, , week = 6

         y
trt        n  y
  placebo  1 16
  drug     5  6
  drug+    5  7

, , week = 11

         y
trt        n  y
  placebo  4 16
  drug     4  8
  drug+    4  8

如何获得上表中每行的行百分比。我尝试了prop.table(),它适用于2个变量表,但对于上面它没有产生正确的行百分比。谢谢你的帮助。

编辑: 我试过了:

prop.table(with(bacteria, table(trt, y, week)))
prop.table(with(bacteria, table(trt, y, week)),1)
prop.table(with(bacteria, table(trt, y, week)),2)
prop.table(with(bacteria, table(trt, y, week)),3)

以上都没有给出正确的行百分比,这将是第一个表:

         y
trt        n  y
  placebo  0.095 0.905
  drug     0.143 0.857
  drug+    0.067 0.933

或者,在上表中获得的data.frame中获得这些百分比也是完美的:

> data.frame(with(bacteria, table(trt, y, week)))
       trt y week Freq
1  placebo n    0    2
2     drug n    0    2
3    drug+ n    0    1
4  placebo y    0   19
5     drug y    0   12
6    drug+ y    0   14
7  placebo n    2    1
8     drug n    2    2
9    drug+ n    2    1
10 placebo y    2   19
11    drug y    2   11
12   drug+ y    2   10
13 placebo n    4    4
14    drug n    4    5
15   drug+ n    4    2
16 placebo y    4   14
17    drug y    4    7
18   drug+ y    4   10
19 placebo n    6    1
20    drug n    6    5
21   drug+ n    6    5
22 placebo y    6   16
23    drug y    6    6
24   drug+ y    6    7
25 placebo n   11    4
26    drug n   11    4
27   drug+ n   11    4
28 placebo y   11   16
29    drug y   11    8
30   drug+ y   11    8

1 个答案:

答案 0 :(得分:4)

以下是几个选项(h.t. @ user20650 for Option 1)

library(MASS)
x <- with(bacteria, table(trt, y, week))

## Option 1
out1 <- prop.table(x, c(1,3))

## Option 2
## apply() to perform prop.table row-wise;
## aperm() to permute the output back to same form as in input:
out2 <- aperm(apply(x,c(1,3),prop.table), c(2,1,3))

out2
# , , week = 0
# 
#          
# trt                n         y
#   placebo 0.09523810 0.9047619
#   drug    0.14285714 0.8571429
#   drug+   0.06666667 0.9333333
# 
# , , week = 2
# 
#          
# trt                n         y
#   placebo 0.05000000 0.9500000
#   drug    0.15384615 0.8461538
#   drug+   0.09090909 0.9090909
# 
# , , week = 4
# 
#          
# trt               n         y
#   placebo 0.2222222 0.7777778
#   drug    0.4166667 0.5833333
#   drug+   0.1666667 0.8333333
# 
# , , week = 6
# 
#          
# trt                n         y
#   placebo 0.05882353 0.9411765
#   drug    0.45454545 0.5454545
#   drug+   0.41666667 0.5833333
# 
# , , week = 11
# 
#          
# trt               n         y
#   placebo 0.2000000 0.8000000
#   drug    0.3333333 0.6666667
#   drug+   0.3333333 0.6666667