Re: [R] search algorithm

From: James Muller <>
Date: Tue 14 Feb 2006 - 00:03:11 EST


I'm not sure how much weight you're putting on efficiency for your algorithm, but that sounds unnecessarily complicated. If your matrices are not too big then maybe something like this would work. Let your matrix be M and your value be a, then

yoursearch <- function(M, a) {

	# generate abs dist vector
	dist <- abs(M[,"X"]-a)

	# which element is min dist
	argmin <- which.min(dist)

	# return corresponding Y value


There are so many ways to do this faster (google for search algorithms if you feel so inclined), but I think simplicity is good unless you have enormous matrices or need to do it a very large number of times.

Anyway, hope this helps


On Mon, Feb 13, 2006 at 01:30:21PM +0100, wrote:
> I have a problem of finding a specific value in a column. For example, I
> have a matrix with say 2 columns
> Now if I have some value of x=-0.6523. I need to find a value in the X
> column that is the closest to my value of x then read off the row number
> and then take the corresponding value in column Y. What I am not sure is
> how to do the first search where I would search by decimal places and take
> the smallest absolute distance between the numbers. For example if he finds
> the first value which is correct in this case - and then 0 and then 6 and
> then 5 but now there is no 2 for that specific decimal place so he would
> calculate the distance between the one before and the one after and see
> which one is smaller. For that which is smaller would be the final X value.
> Can someone please give me a hint on how to proceed. Thanks. mailing list PLEASE do read the posting guide! Received on Tue Feb 14 00:23:45 2006

This archive was generated by hypermail 2.1.8 : Wed 15 Feb 2006 - 13:27:08 EST