[R] Loops

Law, Jason Jason.Law at portlandoregon.gov
Wed Jun 26 00:32:17 CEST 2013


Not sure what you're trying to do, but it looks like most of what you're attempting to do in the code can be done just using vectors rather than loops, at least the inner loop.  For example:

k <- 1.15
l <- exp((1 / k) * (7.16 - 0.44 + 0.12 - 0.016))
z <- (log(1 / p) * l)^k

See ifelse for how to do the if tests on a vector.  In addition, much of the code in your loops doesn't vary with the loop indices and can be moved outside your loop (e.g., setting k = 1.15).  If you really want/need to use loops, you'll have to initialize the vectors/matrices within your loop with some value:

z <- numeric(1000)

Finally, you have some plain syntax errors: 

p[i]=[i+1].

That's not valid R code; '[' is the extraction operator, see help('[').  I'm not sure what you're trying to do there.  Perhaps:

p[i] <- p[i + 1]

HTH,

Jason Law



-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of bett kimutai
Sent: Tuesday, June 25, 2013 1:32 PM
To: r-help at r-project.org
Subject: [R] Loops

Dear All,


I  have spent most of my time trying to figure out how to simulate the number of breaks in a pipe using Monte Carlo simulation.
i have 20,000 individual pipes that i have to run, and for each pipe i have to run 1000 times while checking some conditions and therefore, i have to use a nested loop.
what i would like to have as a final result is a matrix table with with all the individual pipe elements and the simulated runs here is the loop that i tried to create x=20000 y=matrix(x, z)
p=runif(1000)
for(j in 1:20000) {
for(i in 1:1000) {
       k=1.15
    l=exp((1/k)*(7.16-0.44+0.12-0.016))
            
    z[i]=(log(1/p[i])*l)^k

    if (z[i] <=684)
    {
        k1=0.504
        l1=exp((1/k)*(8.01-1.5+0.35+0.45))
        z1[i]=(log(1/p[i])*l1)^k1
    if (z1[i] <=684)
    {
                k2=0.43
        l2=exp((1/k2)*(9.55-2.45+0.40+0.65))
        z2[i]=(log(1/p[i])*l2)^k2
                p[i]=[i+1]
                break()
            }
        }
    }
x[ j ]=[ j+1 ]
}
the last column of the table,  in addition to the simulated runs, i would like to have the summary of the means (for z<=684) of individual row as this means will give me the number of breaks.
i will really appreciate if anyone who can help me figure out how to go about this. pardon me, I am new to R and programming.



Thank you in Advance,

Eliab
    [[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org 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.
	[[alternative HTML version deleted]]



More information about the R-help mailing list