[R] Simulation help
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Wed Feb 25 11:59:42 CET 2004
Spencer Graves <spencer.graves at pdf.com> writes:
> How about the following: > set.seed(5)
> > N <- 8 # later 100000
> > (nPois <- rpois(N, 2))
> [1] 1 3 4 1 0 3 2 3
> > z <- rnorm(sum(nPois))
?
I read the original request as simulating the sum of a
Poisson distributed number of Normals. So I'd suggest
V <- replicate(100000,sum(rnorm(rpois(1,3))))
(Which is obviously a strange distribution since the sum may be empty)
Older versions of R, and Splus want
V <- sapply(1:100000, function(i) sum(rnorm(rpois(1,3))))
> > V <- tapply(z, rep(1:N, nPois), sum)
> > quantile(V, c(0, .05, .25, .5, .75, .95, 1))
> 0% 5% 25% 50% 75% 95%
> 100%
> -2.7812799 -2.4600296 -1.5393631 -1.0803926 0.5800796 1.4626007
> 1.7114409
>
> The same code works in S-Plus 6.2 and R 1.8.1 under Windows
> 2000, though the answers different as S-Plus and R use different
> random number generators. hope this helps. spencer graves
>
> jonathan_wang at sbcglobal.net wrote:
>
> >I am a new R user. As a test, I want to write a simple code that does the following simulation:
> >
> >1. Randomly generate a number from a distribution, say, Poisson. Let's say that number is 3.
> >2. Randomly generate 3 numbers from another distribution, say, Normal.
> >3. Compute the sum of the numbers generated in step 2 and read it into a vector, V.
> >4. Repeat steps 1 through 3 for 100,000 times.
> >5. Derive quantiles (e.g., 0.95th, 0.99th) of V.
> >
> >Any help in getting me going would be greatly appreciated.
> >
> > [[alternative HTML version deleted]]
> >
> >______________________________________________
> >R-help at stat.math.ethz.ch mailing list
> >https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> >PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
> >
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list