[R] r-ish ? how can i improve my code?
Sean O'Riordain
seanpor at acm.org
Wed Oct 15 11:06:36 CEST 2003
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);
More information about the R-help
mailing list