[R] Plot in function

Jim Lemon jim at bitwrit.com.au
Wed Nov 7 10:14:48 CET 2012


On 11/07/2012 03:44 AM, Pauli wrote:
> Hello,
>
> I am a R beginner and I have a question about a litte function I found.
> Here is the code:
>
> # Gambler's Ruin Problem.
> # seed capital:                k
> # rounds:                      n
> # probability of success:                  p
> # number of trials:             N
> # graphical output (yes/no): draw
> # Wait for new graphic (yes/no):   ask
>
> ruin<- function( N = 1, n = 10, k = 1, p = 1 / 2,
>                   draw = FALSE, ask = FALSE ){
>     if(draw)
>       par( ask = ask )
>     r<- 0
>     for( i in 1:N ){
>       x<- k + cumsum (sample( c(-1, 1),replace = TRUE, n,prob = c(1-p, p)))
>       if( min(x)<= 0 ){
>         r<- r + 1
>         if(draw)
>           ruin.plot( k, x, col = "red",main = paste(i, "th trial: ruin!" ) )
>       }
>       else if(draw)
>              ruin.plot( k, x, main = paste( i, "th trial: no ruin" ),ylim =
> c( 0, max(x) ) )
>     }
>     return(r / N)
> }
>
> Now I want to start it with for example
> "ruin(N=100,n=1000,k=50,draw=TRUE,ask=TRUE)" but i received the message,
> that there is an unused argument: (col = "red",main = paste(i, "th trial:
> ruin!" ) ).
> What is wrong with the code?

Hi Pauli,
Since you received the "unused argument" error message, you may have 
defined the "ruin.plot" function somewhere without the "col=" argument. 
I tried changing the call to "ruin.plot" to simply "plot", but your k 
and x values are of different lengths, so they won't plot anyway. I 
think what you may be trying to achieve is more like this:

ruin<-function( N = 1, n = 10, k = 1, p = 1 / 2,
  draw = FALSE, ask = FALSE ){

  if(draw) par( ask = ask )
  r <- 0
  plot(0,xlim=c(0,N),ylim=c(-20,k),type="n",main="Gambler's Ruin plot")
  for( i in 1:N ){
   x <- k + cumsum (sample( c(-1, 1),replace = TRUE, n,prob = c(1-p, p)))
   if( min(x) <= 0 ) {
    r <- r + 1
    if(draw) {
     points(i, x[which.min(x)], col = "red" )
     text(i,x[which.min(x)]-2,"ruin!")
    }
   }
   else if(draw) points(i, x[which.min(x)], col="green")
  }
  return(r / N)
}

ruin(N=100,n=1000,k=50,draw=TRUE,ask=TRUE)

Jim




More information about the R-help mailing list