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!
A contingency table is a special type of frequency distribution table, where two variables are shown simultaneously.
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.
# 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 # ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With