"Teresa Nelson" <jtanelson at centurytel.net> writes:
> Hi there,
>
>
>
> I can get the for-loop to work, I can get the while loop to work. But I
> can't get a for loop to work nested within the while loop - why?
>
What do you mean it doesn't work??
I get:
>
> results
[,1] [,2]
[1,] 1 25
[2,] 2 50
[3,] 3 75
[4,] 4 100
[5,] 5 125
[6,] 6 150
[7,] 7 175
[8,] 8 200
[9,] 9 225
[10,] 10 250
[11,] 11 275
[12,] 12 300
[13,] 0 0
...
[107,] 0 0
[108,] 108 300
[109,] 0 0
[110,] 110 275
[111,] 0 0
[112,] 0 0
[113,] 0 0
[114,] 0 0
[115,] 0 0
[116,] 0 0
[117,] 0 0
[118,] 0 0
[119,] 0 0
[120,] 120 300
If that's not what you expected, then you need to adjust your
expectations. Notice that your k's are effectively
> outer(1:12,1:10)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 2 3 4 5 6 7 8 9 10
[2,] 2 4 6 8 10 12 14 16 18 20
[3,] 3 6 9 12 15 18 21 24 27 30
[4,] 4 8 12 16 20 24 28 32 36 40
[5,] 5 10 15 20 25 30 35 40 45 50
[6,] 6 12 18 24 30 36 42 48 54 60
[7,] 7 14 21 28 35 42 49 56 63 70
[8,] 8 16 24 32 40 48 56 64 72 80
[9,] 9 18 27 36 45 54 63 72 81 90
[10,] 10 20 30 40 50 60 70 80 90 100
[11,] 11 22 33 44 55 66 77 88 99 110
[12,] 12 24 36 48 60 72 84 96 108 120
and that in that table some numbers occur up to five times and others
not at all.
>
> Please help,
>
> Teresa
>
>
> # Why doesn't this nested loop work?
>
> n.max <- 300
> NUM <- 25
>
> n.sim <- 10
> j <- (n.max/NUM)*n.sim
>
> results <- matrix(0, nrow=j, ncol=2)
>
> while(NUM <= n.max){
>
> for(i in 1:n.sim){
>
> k <- (NUM/25)*i
>
> results[k,1] <- k
> results[k,2] <- NUM
>
> }
>
> NUM <- NUM + 25
>
> }
>
> results
>
> #### TRY WHILE LOOP ONLY
>
> results <- matrix(0, nrow=12, ncol=2)
>
> n.max <- 300
> NUM <- 25
>
> while(NUM <= n.max){
>
> k <- NUM/25
>
> results[k,1] <- k
> results[k,2] <- NUM
>
> NUM <- NUM + 25
>
> }
>
> results
>
> # It works, here are the results
>
> # [,1] [,2]
> # [1,] 1 25
> # [2,] 2 50
> # [3,] 3 75
> # [4,] 4 100
> # [5,] 5 125
> # [6,] 6 150
> # [7,] 7 175
> # [8,] 8 200
> # [9,] 9 225
> #[10,] 10 250
> #[11,] 11 275
> #[12,] 12 300
>
>
>
> ### Try For Loop Only
>
> n.sim <- 10
> NUM <- 25
>
> results <- matrix(0, nrow=10, ncol=2)
>
> for(i in 1:n.sim){
>
> results[i,1] <- i
> results[i,2] <- NUM
>
> }
>
> results
>
> # it works, here are the results
> # [,1] [,2]
> # [1,] 1 25
> # [2,] 2 25
> # [3,] 3 25
> # [4,] 4 25
> # [5,] 5 25
> # [6,] 6 25
> # [7,] 7 25
> # [8,] 8 25
> # [9,] 9 25
> #[10,] 10 25
> ______________________________________________
> 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
--
O__ ---- Peter Dalgaard ??ster Farimagsgade 5, Entr.B
c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907