5

例子:

x <- c( 1, NA, 0, 1)
y <- c(NA, NA, 0, 1)
table(x,y, useNA="always") # --->
#       y
# x      0 1 <NA>
#   0    1 0    0
#   1    0 1    1
#  <NA>  0 0    1

我的问题是:

a <- c(NA, NA, NA, NA)
b <- c(1, 1, 1, 1)
table(a, b, useNA="always") ## --> It is 1X2 matrix. 
#       b
# a      1 <NA>
#   <NA> 4    0

我想得到一个 3X3 表,其列名、行名和维度与上面的示例相同。然后我将为该表应用 chisq.test。非常感谢您的回答!

4

1 回答 1

6

You can achieve this by converting both a and b into factors with the same levels. This works because factor vectors keep track of all possible values (aka levels) that their elements might take, even when they in fact contain just a subset of those.

a <- c(NA, NA, NA, NA)
b <- c(1, 1, 1, 1)

levs <- c(0, 1)

table(a = factor(a, levels = levs), 
      b = factor(b, levels = levs), 
      useNA = "always")
#       b
# a      0 1 <NA>
#   0    0 0    0
#   1    0 0    0
#   <NA> 0 4    0
于 2012-10-09T18:55:22.317 回答