Friday, 15 July 2011

r - How do I create a biased random number generator? -



r - How do I create a biased random number generator? -

i need create random number generator biases selection of value classes on others. example:

if tell homecoming value between 1 , 5, unbiased assign 20% probability each. if wanted 2 , 3 have probabilities of 30% each, others downwards weighted accordingly.

how might go doing in r range of 1-16 without restricting output integer?<-- problem solved keegan below. code below uses modification of now, method run in end.

new issue:when run walk has 2 problems:

1) returns same path (it's supposed random , hence highly unlikely ever give same path twice).

2) if run walkw(s) 1 time again fails, saying xy coordinates no longer exist. wasn't issue before changed sample pool ubstep , bstep, i'm failing see how , why happened or how prepare it.

i've provided core code before. you'll need binary image in working directory labeled "testmap2.png" ebimage bundle run it.

to generate error: run entire code once, run line walkw(s) again

thanks in advance!

library("ebimage") #calculating z p<-95 #dont worry step.max<-125 #number of steps allowed walk stride<-131 #maximum pixel distance covered per step. s<-step.max #step size pool ubstep<-c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20) bstep<-c(1,3,5,7,9,11,13,15,17,19) #bring in background image pic<-readimage("testmap2.png",all=true,package="ebimage") rpic<-as.raster(pic) #start walking walkw <- function(n.times=125, xlim=c(0,615), ylim=c(0,615), start=c(520,100), stepsize=c(stride,stride)) { plot(c(0,0),type="n",xlim=xlim,ylim=ylim, xlab="x", ylab="y", col="black",col.lab="black") lim <- par() rasterimage(rpic, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4]) x <- start[1] y <- start[2] steps <- 1/sample(ubstep,1) bsteps<-sample(bstep,1) steps.y <- c(steps,-steps,0) steps.x <- c(steps[bsteps],-steps,0) points(x,y,pch=16,col="green",cex=1) (i in 1:n.times) { repeat { xi <- stepsize[1]*sample(steps.x,1) yi <- stepsize[2]*sample(steps.y,1) newx <- x+xi newy <- y+yi if (newx>xlim[1] && newx<xlim[2] && newy>ylim[1] && newy<ylim[2]) break } lines(c(x,newx),c(y,newy),col="cyan") x <- newx y <- newy ##dont worry function. calculates z compared predefined p. step.prob<-function(n.times=step.max){ cs<-pic[x,y,1] cs.max<-1 step.num<-i sp<-(((cs/cs.max)*(1-(step.num/step.max))+(step.num/step.max))*100) } z<-step.prob(1) #draw lines , dots create pretty if(z>p){points(newx,newy,pch=9,col="white",cex=1)} if(z>p)break if(i<step.max){points(newx,newy,pch="*",col="yellow",cex=1)} } } set.seed(101) walkw(s)

using prob argument sample, can set weights like.

sample(1:5,prob=c(.05,.05,.1,.4,.4))

to draw 1 number distribution:

sample(1:5,1,prob=c(.05,.05,.1,.4,.4))

to draw many:

sample(1:5,50,prob=c(.05,.05,.1,.4,.4),replace=true)

r random

No comments:

Post a Comment