[R] Help on "looping problem" needed!

Dimitris Rizopoulos dimitris.rizopoulos at med.kuleuven.be
Mon Jul 23 17:37:38 CEST 2007


try this:

tol <- 0.000001
mat <- matrix(as.numeric(NA), 1000, 5)
k <- 1
while(any(is.na(mat))){
    x <- rnorm(1000, sd = 0.02)
    if (abs(mean(x)) < tol) {
        mat[, k] <- x
        k <- k + 1
    }
}

abs(colMeans(mat))
par(mfrow = c(2, 3))
apply(mat, 2, hist)


I hope it helps.

Best,
Dimitris

----
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven

Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/(0)16/336899
Fax: +32/(0)16/337015
Web: http://med.kuleuven.be/biostat/
     http://www.student.kuleuven.be/~m0390867/dimitris.htm


----- Original Message ----- 
From: "Ing. Michal Kneifl, Ph.D." <xkneifl at mendelu.cz>
To: "Rhelp" <r-help at stat.math.ethz.ch>
Sent: Monday, July 23, 2007 4:40 PM
Subject: [R] Help on "looping problem" needed!


>I am wondering if someone could help me out with following problem:
> I have written a for loop which generates a random normal 
> distribution
> let us say 1000 times.
> When the restriction is met (mean<0.000001), the loop stops, prints
> the mean value and plots a histogram.
>
> for(i in 1:1000) {
> a<-rnorm(1000,0,.2)
> b<-abs(mean(a))
> if(b>.000001) next else {print(b);hist(a);break}}
>
> How to reshape the loop when I want to find at least 5 distibutions
> that meet my restriction and save them (assign) under
> names R1....R5.
> Could you help me please?
>
> Michael
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 


Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm



More information about the R-help mailing list