[R] sapply() and Monte Carlo

Robin Hankin r.hankin at auckland.ac.nz
Wed Jun 26 06:51:44 CEST 2002


Dear Helplist

Some time ago, Professor Ripley gave me a tip which I thought was very
very useful for Monte Carlo simulation; I thought I'd pass it on to
the list, and ask whether this or a similar example could be added to
the sapply() manpage.

Suppose I have ten N(0,1) random variables and I'm interested in the
pair that are closest together:

R> min(diff(sort(rnorm(10))))
[1] 0.04438955

To generate a PDF for this statistic one can use sapply() as follows:

R> func <- function(n){min(diff(sort(rnorm(n))))}
R> hist(sapply(rep(10,999),func),col="gray")

This is *soooo* much better than having a loop!  Cheers everyone!
Anyone got any other interesting uses of sapply()?  Would anyone on
the List be interested in a collection specifically of neat R
oneliners?



-- 

Robin Hankin, Lecturer,
School of Geographical and Environmental Science
Private Bag 92019 Auckland
New Zealand

r.hankin at auckland.ac.nz
tel 0064-9-373-7599 x6820; FAX 0064-9-373-7042
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list