lundi 29 juin 2015

match a pattern in a matrix

I would like to find missingness patterns in a matrix and extract data matching a particular pattern. So, I have this matrix below (mydata) and identified 4 missingness patterns in the matrix (pattern), but I couldn't extract data from the matrix matching a particular pattern. For example the pattern "1 NA NA" (second row of the pattern matrix) should only extract rows 5 and 10 of the matrix:

[5,]   87   NA   NA
[10,]  96   NA   NA

.

mydata <- cbind(c(78, 84, 84, 85, 87, 91, 92, 94, 94, 96, 99, 105, 
                 105, 106, 108, 112, 113, 115, 118, 134),
                c(13, 9, 10, 10, NA, 3, 12, 3, 13, NA, 6, 12, 14, 
                  10, NA, 10, 14, 14, 12, 11),
                c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 7, 10, 
                  11, 15, 10, 10, 12, 14, 16, 12)
               )
mydata

       [,1] [,2] [,3]
 [1,]   78   13   NA
 [2,]   84    9   NA
 [3,]   84   10   NA
 [4,]   85   10   NA
 [5,]   87   NA   NA
 [6,]   91    3   NA
 [7,]   92   12   NA
 [8,]   94    3   NA
 [9,]   94   13   NA
[10,]   96   NA   NA
[11,]   99    6    7
[12,]  105   12   10
[13,]  105   14   11
[14,]  106   10   15
[15,]  108   NA   10
[16,]  112   10   10
[17,]  113   14   12
[18,]  115   14   14
[19,]  118   12   16
[20,]  134   11   12


pattern <- unique(ifelse(!is.na(mydata), 1, NA))
pattern

      [,1] [,2] [,3]
[1,]    1    1   NA
[2,]    1   NA   NA
[3,]    1    1    1
[4,]    1   NA    1

Aucun commentaire:

Enregistrer un commentaire