Skip to content
Back to formatted view

Raw Message

Message-ID: <Pine.A41.4.58.0402180833480.132464@homer05.u.washington.edu>
Date: 2004-02-18T16:41:05Z
From: Thomas Lumley
Subject: How to repeat a procedure
In-Reply-To: <OF5F33C567.A1B22A84-ON85256E3E.0055D43D@health.state.ny.us>

On Wed, 18 Feb 2004, Haiyan Chen wrote:

> Hello,
>
> 1. After I generate a 100x50 matrix by x3<-matrix(0,100,50);for (i in
> 1:100) {x1<-rpois(50, mu[i]);x2<-x1; x2[runif(50)<.01]<-0; x3[i,]<-x2},

YOu can do this without the loop, eg

x3<-rpois(50*100, rep(mu,each=100))
x3<-ifelse(runif(50*100)<0.01, 0, x3)
x3<-matrix(x3, ncol=50)

> 2. I want to calculate means and sample variances of each row and create a
> new matrix 100x2;

means<-apply(x3,2,mean)
vars<-apply(x3,2,var)
cbind(means,vars)

> 3. I then want to repeat above procedure 500 times so that eventually I
> will have 500 100x2 matrices.

make.a.matrix<-function(...){
	x3<-rpois(50*100, rep(mu,each=100))
	x3<-ifelse(runif(50*100)<0.01, 0, x3)
	x3<-matrix(x3, ncol=50)
	cbind(apply(x3,2,mean), apply(x3,2, var))
}

many.matrices<-lapply(1:500, make.a.matrix)

gives a list of 500 matrices.  This isn't quite the most efficient
solution, but it's not bad.


	-thomas