[R] r-ish ? how can i improve my code?

Patrick Burns pburns at pburns.seanet.com
Wed Oct 15 11:42:59 CEST 2003


For this particular problem you can probably use
polar coordinates.

But something similar to your code could be:

x <- runif(900)
y <- runif(900)
z <- sqrt(x^2 + y^2)
okay <- z < 1
while(any(!okay)) {
    n.bad <- sum(!okay)
    x[!okay] <- runif(n.bad)
    y[!okay] <- runif(n.bad)
    z <- sqrt(x^2 + y^2)  # restricting to !okay may or may not be useful
    okay <- z < 1
}



Patrick Burns

Burns Statistics
patrick at burns-stat.com
+44 (0)20 8525 0696
http://www.burns-stat.com
(home of S Poetry and "A Guide for the Unwilling S User")

Sean O'Riordain wrote:

> Hi Folks,
>
> I'm trying to learn R.  One of my intentions is to do some Monte-Carlo 
> type modelling of road "accidents".
>
> Below, to simplify things, I've appended a little program which does a 
> 'monte-carlo' type simulation.  However, it is written in a way which 
> seems a bit un-natural in R.  Could someone help me make this a bit 
> more R-ish please?
>
> Or is there a completely different approach I should be taking?
>
> Many thanks in advance,
> Sean O'Riordain
> seanpor AT acm.org
>
>
> --------------------------------------------
> n <- 900; # number of valid items required...
>
> x <- numeric(n);
> y <- numeric(n);
> z <- numeric(n);
>
> c <- 1;  # current 'array' pointer
> tc <- 0; # total items actually looked at...
>
> while (c <= n) {
>     x[c] = runif(1, 0, 1);
>     y[c] = runif(1, 0, 1);
>
>     z[c] = sqrt(x[c]^2 + y[c]^2);
>     if (z[c] < 1)
>         c <- c + 1;
>     tc <- tc + 1;
> }
>
> print("'overwork' ratio");
> print(tc/(c-1));
> plot(x,y);
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>
>




More information about the R-help mailing list