# [R] searching for specific row in matrix

From: Esmail Bonakdarian <esmail.js_at_gmail.com>
Date: Wed, 11 Jun 2008 07:58:07 -0400

Hi,

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_at_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. Received on Wed 11 Jun 2008 - 14:31:33 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 11 Jun 2008 - 15:00:41 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.