Search code examples
rarraysxtabs

Extracting an xtabs subarray from an array given condition in R


There is a 2-way table which is an array from xtabs(), like this:

    A  B
12  0  0
20  1  0
41 22 16
49  4  8
50  0  1
56  3  2
57  4  2
59  1  0
63  0  3
64  2  1
65  0  0
68  0  1
71  2  7
72  2  1
73  9  7
78  0  1

How can one extract a subtable such that each cell must be 2 or greater? The resulting table would look like this:

    A  B
41 22 16
49  4  8
56  3  2
57  4  2
71  2  7
73  9  7

Solution

  • Filter it like you would any other matrix.

    tab[rowSums(tab < 2) == 0,]
    #     A  B
    # 41 22 16
    # 49  4  8
    # 56  3  2
    # 57  4  2
    # 71  2  7
    # 73  9  7
    

    Data

    tab <- structure(c(0L, 1L, 22L, 4L, 0L, 3L, 4L, 1L, 0L, 2L, 0L, 0L, 2L, 2L, 9L, 0L, 0L, 0L, 16L, 8L, 1L, 2L, 2L, 0L, 3L, 1L, 0L, 1L, 7L, 1L, 7L, 1L), dim = c(16L, 2L), dimnames = list(c("12", "20", "41", "49", "50", "56", "57", "59", "63", "64", "65", "68", "71", "72", "73", "78"), c("A", "B")), class = c("xtabs", "table"))