Re: [R] searching for specific row in matrix

From: Esmail Bonakdarian <esmail.js_at_gmail.com>
Date: Wed, 11 Jun 2008 09:29:15 -0400

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



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 - 15:21:35 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 - 16:30: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.

list of date sections of archive