r语言 - 如何在 3d 列联选项卡中选择部分表?



这似乎是一个新问题,但我就是想不通。我正在查看 3D 列联表,我想对部分表进行分析。下面是一些示例数据:

df2 <- data.frame(Gender = c(rep("M", 6), rep("F", 6)), Beliefs = c(rep("Fund", 2), rep("Mod", 2), rep("Liberal", 2), rep("Fund", 2), rep("Mod", 2), rep("Liberal", 2)), Afterlife = c(rep(c("Yes", "No"), 6)), Count = c(252, 43, 274, 47, 226, 100, 420, 50, 415, 50, 273, 83))
df2.tab <- xtabs(Count ~ Beliefs + Afterlife + Gender, data = df2)

最初,性别是我的 Z 变量。但我想比较不同层次信仰的部分表格。当然,我可以创建一个将信念作为我的分组变量的 xtabs,但即便如此,我也无法弄清楚如何独立选择部分表(或 Z 级别(,以便我可以找到每个部分表的 OR,例如,使用 epitools::oddsratio.wald

多谢!

下面尝试通过示例来解释apply如何在这里有用:

printchk <- function(x) {print(x); print(class(x)); cat("------n")}
tab <- array(1:8,dim=c(2,2,2))
printchk(tab)
#, , 1
#
#     [,1] [,2]
#[1,]    1    3
#[2,]    2    4
#
#, , 2
#
#     [,1] [,2]
#[1,]    5    7
#[2,]    6    8
#
#[1] "array"
#------

跨层处理组合行

invisible(apply(tab, 1, printchk))
#     [,1] [,2]
#[1,]    1    5
#[2,]    3    7
#[1] "matrix"
#------
#     [,1] [,2]
#[1,]    2    6
#[2,]    4    8
#[1] "matrix"
#------

跨地层使用组合柱

invisible(apply(tab, 2, printchk))
#     [,1] [,2]
#[1,]    1    5
#[2,]    2    6
#[1] "matrix"
#------
#     [,1] [,2]
#[1,]    3    7
#[2,]    4    8
#[1] "matrix"
#------

使用地层

invisible(apply(tab, 3, printchk))
#     [,1] [,2]
#[1,]    1    3
#[2,]    2    4
#[1] "matrix"
#------
#     [,1] [,2]
#[1,]    5    7
#[2,]    6    8
#[1] "matrix"
#------

因此,在不更改维度或结构的情况下,您可以使用apply调用来比较数组的不同部分。

oddsratio <- function(x) (x[1,1]/x[2,1]) / (x[1,2]/x[2,2])
apply(tab, 1, oddsratio)
##Expecting: (1/3)/(5/7) = 0.46
##           (2/4)/(6/8) = 0.66
#[1] 0.4666667 0.6666667

是的,按预期工作。

多个维度

然后可以扩展此逻辑以同时使用多个维度,例如:

invisible(apply(tab, c(1,2), printchk))
#[1] 1 5
#[1] "integer"
#------
#[1] 2 6
#[1] "integer"
#------
#[1] 3 7
#[1] "integer"
#------
#[1] 4 8
#[1] "integer"
#------

最新更新