[R] searching for specific row in matrix

Esmail Bonakdarian esmail.js at gmail.com
Wed Jun 11 15:29:15 CEST 2008


Henrique Dallazuanna wrote:
> Try this:
> 
> which(apply(t(m) == target, 2, all))

Wow! .. talk about concise! Neat! Thanks.

This will return all matches correct? So if I only wanted
the first I'd simply subscript [1] into it.

Do you think the fact that it searches the whole matrix instead
of stopping when it finds a match may slow it down?

This is my own solution I came up with in the meantime,
looks rather pedestrian compared to your one line, but it will
drop out immediately once if finds the target. Yours looks (based
simply on appearance :-) faster. Having no feel for the language
I may just have to time them.


I would assume that your solution would be faster simple since it's
using built-in language constructs which are optimized (and implemented
in C?) instead of my own interpreted way.


# return index of target in pop, else -1
searchPop <- function(pop, target)
{
     rows = length(pop[1,])
     for(i in 1:rows)
     {
         result = (pop[i,] == target)
         if (sum(which(result==FALSE)) == 0)
             return(i)
     }

     return (-1)
}


idx=searchPop(pop, target)

if (idx < 0)
{
     cat("NOT found\n")
} else
     cat("Found at position ", idx, "\n")



Esmail
> -- 
> Henrique Dallazuanna
> Curitiba-Paraná-Brasil
> 25° 25' 40" S 49° 16' 22" O



More information about the R-help mailing list