如何用R中的两个变量创建3乘3列联表

时间:2022-02-12 01:12:30

Example:

例:

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

My question is:

我的问题是:

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

I want to get a 3X3 table with the same colnames, rownames and dimensions as the example above.. Then I will apply chisq.test for the table. Thank you very much for your answers!

我想获得一个3X3表,其中包含与上面示例相同的colnames,rownames和dimension。然后我将chisq.test应用于表。非常感谢您的回答!

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和b转换为具有相同级别的因子来实现此目的。这是因为因子向量跟踪其元素可能采用的所有可能值(也称为级别),即使它们实际上只包含其中的一部分。

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

#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和b转换为具有相同级别的因子来实现此目的。这是因为因子向量跟踪其元素可能采用的所有可能值(也称为级别),即使它们实际上只包含其中的一部分。

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