0

可能重复:
如何为三维表创建 prop.table()?

我是R新手,我一直在研究三通表,需要一些帮助。以下是表格描述dput

mytable <- structure(c(42L, 151L, 313L, 69L, 22L, 46L, 47L, 24L, 17L, 36L, 108L, 16L), .Dim = c(2L, 2L, 3L), .Dimnames = list(c("0", "1" ), c("female", "male"), c("adult", "child", "unknown")), class = "table") 

我想通过使用属性名称来访问该表的元素。例如: mytable["0"]["female"]["adult"]可以这样做吗?

另外,我正在尝试计算比例。这是我的桌子......

, , adult

      female male
    0     42  313
    1    151   69

    , , child

      female male
    0     22   47
    1     46   24

    , , unknown

      female male
    0     17  108
    1     36   16

我想计算年龄组-sex-0|1 的比例。当我运行prop.table(mytable)它时,它正在计算细胞的比例,但它正在考虑所有三个年龄组。

, , adult

          female       male
    0 0.04713805 0.35129068
    1 0.16947250 0.07744108

    , , child

          female       male
    0 0.02469136 0.05274972
    1 0.05162738 0.02693603

    , , unknown

          female       male
    0 0.01907969 0.12121212
    1 0.04040404 0.01795735

我想要每个年龄组和性别的比例。例如:在所有成年人中,有 1 的女性占 78%。我们如何做到这一点 ?

4

2 回答 2

1

这就是你所追求的吗?

数据:

test <- structure(c(42L, 151L, 313L, 69L, 22L, 46L, 47L, 24L, 17L, 36L, 108L, 16L), .Dim = c(2L, 2L, 3L), .Dimnames = list(c("0", "1" ), c("female", "male"), c("adult", "child", "unknown")), class = "table") 

2获取每个子表 ( ) 中的列百分比 ( 3):

prop.table(test,c(2,3))

结果是:

, , adult

     female      male
0 0.2176166 0.8193717
1 0.7823834 0.1806283

, , child

     female      male
0 0.3235294 0.6619718
1 0.6764706 0.3380282

, , unknown

     female      male
0 0.3207547 0.8709677
1 0.6792453 0.1290323
于 2013-02-03T01:05:02.293 回答
1

一种更简单的方法可能是使您的表成为 data.frame:

df <- as.data.frame(mytable)

然后根据需要获取零值:

df[df$Var1 == 0,]

对于比例,你可以这样做:

df <- transform(df,total = ave(Freq, Var3, FUN = sum))
# get totals within adult/child/unkown

df <- transform(df,props = Freq/total)
# make proportions



#    > df
#   Var1   Var2    Var3 Freq total      props
#1     0 female   adult   42   575 0.07304348
#2     1 female   adult  151   575 0.26260870
#3     0   male   adult  313   575 0.54434783
#4     1   male   adult   69   575 0.12000000
#5     0 female   child   22   139 0.15827338
#6     1 female   child   46   139 0.33093525
#7     0   male   child   47   139 0.33812950
#8     1   male   child   24   139 0.17266187
#9     0 female unknown   17   177 0.09604520
#10    1 female unknown   36   177 0.20338983
#11    0   male unknown  108   177 0.61016949
#12    1   male unknown   16   177 0.09039548
于 2013-02-02T23:44:48.587 回答