R-alpha: coding problem

Bill Simpson (wsimpson@uwinnipeg.ca)
Fri, 21 Feb 1997 13:56:42 -0600 (CST)


Date: Fri, 21 Feb 1997 13:56:42 -0600 (CST)
From: Bill Simpson <wsimpson@uwinnipeg.ca>
To: r-testers <r-testers@stat.math.ethz.ch>
Subject: R-alpha: coding problem

I have noticed that the messages on this list seem to be at a very high
level.  Most are concerned with bugs in R and incompatibilities with
SPlus.

Is it OK to ask questions about plain old R programming here?  Or should I
do that on SPlus mailing list?

Here is my coding problem.
I have a 2 frame movie.
Frame 1 contains a random cloud of points (2D Poisson process).
Frame 2 contains 2 kinds of dots:
noise dots are placed at random (2D Poisson process)
signal dots are shifted versions of dots in frame 1 (all have same
shift size and direction).

For each dot in frame 1, I want to find its nearest neighbour in
frame 2. Here is my (pathetic) code:

# nearest neighbour distance simulation

gen.frames<-function(nnoise, nsignal, disp)
{
ntotal<-nsignal+nnoise
r<<-NULL
dir<<-NULL

#generate noise dots
nx1<-runif(nnoise,0,4095)
nx2<-runif(nnoise,0,4095)
ny1<-runif(nnoise,0,4095)
ny2<-runif(nnoise,0,4095)

#generate signal dots
sx1<-runif(nsignal,0,4095)
sx2<-sx1
sy1<-runif(nsignal,0,4095)
sy2<-sy1+disp
sy2<-ifelse(sy2>4095, sy2-4096,sy2) #wrap around

#put signal and noise dots together
tx1<-c(nx1,sx1)
tx2<-c(nx2,sx2)
ty1<-c(ny1,sy1)
ty2<-c(ny2,sy2)

#for each dot in frame 1, find its nearest neighbour in frame 2
for(i in 1:ntotal)
	{
	rbest<-9999
	for(j in 1:ntotal)
		{
		xd<-tx2[i]-tx1[j]
		yd<-ty2[i]-ty1[j]
		rr<-xd^2 + yd^2
		if(rr<rbest)
			{
			r.temp<-sqrt(rr)
			dir.temp<- atan2(yd,xd)
			}
		}
	if(i!=j)
		{
		r<<-c(r,r.temp)
		dir<<-c(dir,dir.temp)
		}
	}

}
The vector r contains the nearest neighbour distance for each dot.
The vector dir contains the nearest neighbour direction for each dot.

This code doesn't even work.  I get the error message:
Error: Object "r.temp" not found

It seems terribly inefficient also.
For each dot in frame 1, it computes the distance to every dot in
frame 2.  Then the smallest one is used.
Can anyone help me make it better?

Thanks very much for any help.

Bill Simpson

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
r-testers mailing list -- For info or help, send "info" or "help",
To [un]subscribe, send "[un]subscribe"
(in the "body", not the subject !)  To: r-testers-request@stat.math.ethz.ch
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-