[R] searching for specific row in matrix
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  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)
if (idx < 0)
cat("Found at position ", idx, "\n")
> Henrique Dallazuanna
> 25° 25' 40" S 49° 16' 22" O
More information about the R-help