1

I need some help to create a n-way frequency table.

I am using the code below:

 tab <- table(VAR1,VAR2,VAR3)
finaltab <- ftable(tab,row.vars=c(2,3))
print(finaltab)

VAR1, VAR2 and VAR3 are all factor variables. By doing this, I produce the following table:

Table 1

But since VAR2 and VAR3 have several categories, I got a lot of lines with "0" and I which to remove those lines to keep in which category of VAR2 only frequencies for the categories of VAR3 that really have frequency values, as follows:

First table with the situation and second table with the desired output

Does anyone knows how to do it, either by subsetting the table I created first or using another function that doesn't return all levels of VAR3 in each VAR2 category but only those which actually have frequencies?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • A lot of people on Stack Overflow use tags to search for questions they have knowledge of/interest in. If you don't add the language as tag, your question will not get a lot of views. – Ivar Feb 03 '16 at 11:07

1 Answers1

0

Contingency tables have the same number of rows in every category. If you remove rows from one category you no longer have a table but a matrix.

t <- structure(c(0L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 1L, 1L), .Dim = c(3L, 2L, 3L), .Dimnames = structure(list(c("A", "B", "C"), c("A", "B"), c("A", "B", "C")), .Names = c("","", "")), class = "table")
> (ft <- ftable(t, row.vars=c(2,3)))
     A B C

A A  0 0 1
  B  1 1 1
  C  0 1 0
B A  1 1 0
  B  0 0 0
  C  1 1 1
> ft[apply(ft, 1, any), ]
     [,1] [,2] [,3]
[1,]    0    0    1
[2,]    1    1    1
[3,]    0    1    0
[4,]    1    1    0
[5,]    1    1    1

The unfortunate effect of subsetting the table is that names are lost. This can be mitigated to some extent by coercing the table to a matrix before taking the subset, but the printed output still isn't as pretty as that of a contengency table.

> as.matrix(ft)[apply(ft, 1, any), ]

_     A B C
  A_A 0 0 1
  A_B 1 1 1
  A_C 0 1 0
  B_A 1 1 0
  B_C 1 1 1
Ernest A
  • 7,526
  • 8
  • 34
  • 40