[R] r-ish ? how can i improve my code?
Spencer Graves
spencer.graves at pdf.com
Wed Oct 15 11:40:24 CEST 2003
1. I suggest you avoid using "c" as a loop index, as it conflicts
with the name of a function. R is smart enough to figure out the
difference in some cases but not in all.
2. How about the following:
n <- 900
x <- runif(n)
y <- runif(n)
z <- sqrt(x^2+y^2)
print(list(Overwork.ratio = n/sum(z<1)))
plot(x, y)
theta <- seq(0, pi/2, length=31)
lines(sin(theta), cos(theta))
######################
This won't give you n numbers z < 1. If you need exactly that,
what about first generating, say, 2*n, then either throwing away the
excess or generating another 2*n if you don't have enough? You can use
a recursive function for this, which would almost never recurse with 2*n
but might with 1.1*n.
hope this helps. spencer graves
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