Hi, I have matrix of bits and a target vector. Is there an efficient way to search the rows of the matrix for the target? I am interested in the first row index where target is found.
Example: > source("lookup.R") [,1] [,2] [,3] [,4] [,5] [1,] 1 0 1 1 0 [2,] 1 1 0 1 0 [3,] 0 0 1 0 0 [4,] 1 0 0 1 1 [5,] 1 0 1 1 1 [6,] 1 1 0 0 1 [7,] 1 0 0 1 1 [8,] 0 0 1 1 1 [9,] 0 1 1 0 1 [10,] 0 0 0 1 0 target: 1 1 0 1 1 Should return -1 (or some other indicator) since the target was not found in any of the rows. > source("lookup.R") [,1] [,2] [,3] [,4] [,5] [1,] 0 0 1 1 0 [2,] 1 0 0 0 0 [3,] 1 0 0 0 0 [4,] 1 1 0 0 0 [5,] 1 1 1 0 0 [6,] 0 0 1 1 0 [7,] 0 1 1 1 0 [8,] 0 0 1 1 0 [9,] 1 1 0 1 1 [10,] 1 0 1 0 0 target: 1 1 0 1 1 Should return 9 since the target was found in row 9 If the target is found, it is no longer necessary to keep searching the rest of the matrix (which may be quite large) The data/size etc may change of course, but target will always have the same number of "columns" as the matrix. I tried variations of "which", and a for loop comparing pop[i,] to target without much success, nor did google yield any results. I am hoping someone here can provide a suggestion. Thanks, EB --------------------------------------------- # Here is the code that generates the above data create_bin_string <- function(len) { sample(0:1, len, replace=T) } ROWS = 10 COLS = 5 pop = matrix(create_bin_string(ROWS*COLS), ROWS, COLS, byrow=T) target=c(1, 1, 0, 1, 1) # my population print(pop) # I am looking for the index of this in pop # if present (else -1?) cat("\ntarget: ", target, "\n") ## ## this is NOT working ## plus it would continue to search ## after it found the target ## for(i in ROWS) if (pop[i,] == target) cat("\nfound in row: ", i, "\n\n") ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.