R-beta: help with R simulation

Bill Simpson (wsimpson@uwinnipeg.ca)
Fri, 5 Sep 1997 15:47:46 -0500 (CDT)


To: r-help@stat.math.ethz.ch
Date: Fri, 5 Sep 1997 15:47:46 -0500 (CDT)
From: Bill Simpson <wsimpson@uwinnipeg.ca>
To: r-help@stat.math.ethz.ch
Subject: R-beta: help with R simulation

[[this bounced first, because it has 'help' in the Subject line ...
  -- Martin Maechler
]]


I am a complete novice R programmer. (Though I know C quite well)

I am trying to write some R code to do the following simulation.

There is a 2-frame "movie" of noise and signal dots.  the noise
dots have random positions in each frame.  The signal dots are
placed randomly in frame 1, but in frame 2 each signal dot's y
coordinate is increment by jump (the dots jump upwards).
I want to find the x and y distance from each dot in frame 1 to its
nearest neighbour in frame 2.  In the simulation I will find the mean
x and mean y distance for a given pair of frames.  Many pairs of
frames will be generated, and the distribution of the mean nearest
neighbour distances (x and y) will be computed.

The code below is my feeble attempt to do the simulation.
So far as I know, it doesn't work.  Any help appreciated!
(I am using Mac version of R)

Bill Simpson

# nearest neighbour distance simulation
# for dynamic noise dots

do.sim<-function(nnoise, nsignal, jump)
{
ntotal<-nsignal+nnoise
x<<-NULL
y<<-NULL
x.temp<-0
y.temp<-0

#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+jump
sy2<-ifelse(sy2>4095, sy2-4096,sy2) #wrap around

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

#compute distance to nearest neighbour (x and y) in frame 2 
#for each dot in frame 1
for(i in 1:ntotal)
	{
	rbest<-2*(4096^2)
	for(j in 1:ntotal)
		{
		xd<-tx2[i]-tx1[j]
		yd<-ty2[i]-ty1[j]
		rr<-xd^2 + yd^2
		if(rr<rbest)
			{
			rbest<-rr
			x.temp<-xd
			y.temp<-yd
			}
		}
	x<<-c(x,x.temp)
	y<<-c(y,y.temp)
	}
}
		
		
sim<-function(nnoise, nsignal, jump)
{
xm<<-NULL
ym<<-NULL

for(i in 1:10)
	{
	do.sim(nnoise, nsignal, jump)
	xm<<-c(xm,mean(x))
	ym<<-c(ym,mean(y))
	}
}





=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request@stat.math.ethz.ch
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=