Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create 3 by 3 Contingency table with two variables in R

Tags:

r

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!

like image 805
Matt Avatar asked Oct 09 '12 18:10

Matt


People also ask

Can a contingency table use two numerical variables?

A contingency table is a special type of frequency distribution table, where two variables are shown simultaneously.

Can a contingency table have 3 variables?

A three-way contingency table is a cross-classification of observations by the levels of three categorical variables. More generally, k-way contingency tables classify observations by levels of k categorical variables.

How do you make a 3 way table in R?

# Mock data: n <- 100 mys <- function(x) sample(x, size = n, replace = TRUE) A <- mys(letters[1:3]) B <- mys(LETTERS[1:4]) C <- mys(paste(1:5)) # Three way table: table(A,B,C, useNA = "always") #, , C = 1 # # B #A A B C D <NA> # a 0 2 0 1 0 # b 2 1 0 0 0 # c 3 0 2 2 0 # <NA> 0 0 0 0 0 # #, , C = 2 # # B # ...


1 Answers

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
like image 127
Josh O'Brien Avatar answered Nov 02 '22 23:11

Josh O'Brien