Home > database >  Creating a 3-way contingency table in R
Creating a 3-way contingency table in R

Time:11-09

I'm struggling on creating a contingency table for the following situation:

"Blood groups of peptic ulcer and control patients in London, Manchester and Newcastle were recorded in a case-control study. Blood groups A and O were represented in a factor B with two levels; the cities mentioned were represented as a factor C with three levels, L, M and N; and U represented a factor with two levels, Control and Ulcer. In this case-control study it is appropriate to treat B as a response factor and C and U both as covariate factors." The vectors are given as

B=c("A","A","A","A","A","A","O","O","O","O","O","O")
C=c("L","L","M","M","N","N","L","L","M","M","N","N")
U=c("C","U","C","U","C","U","C","U","C","U","C","U")
count=c(4219,579,3775,246,5261,219,4578,911,4532,361,6598,396)

I tried creating a table using the code

three=xtabs(~B C U,data=count)
ftable(three)

But get an error message

Error in eval(predvars, data, env) : 
  numeric 'envir' arg not of length one

Is there a way to fix this issue and create the accurate table?

CodePudding user response:

You can create a data.frame and use then xtabs:

xtabs(count~B C U, data.frame(B, C, U, count))
#, , U = C
#
#   C
#B      L    M    N
#  A 4219 3775 5261
#  O 4578 4532 6598
#
#, , U = U
#
#   C
#B      L    M    N
#  A  579  246  219
#  O  911  361  396
  •  Tags:  
  • r
  • Related