Thursday, 15 August 2013

loop within a loop in R

loop within a loop in R

I'm trying to write a loop within a loop in R, but it seems only the inner
loop is working:
test <- rbind(c(1:30), c(31:60), c(61:90), c(91:120))
test
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
26 27 28 29 30
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
56 57 58 59 60
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
86 87 88 89 90
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
110 111 112 113 114 115 116 117 118 119 120
Here's what I've been written:
b<- data.frame()
n<-1
i<-1
c<- data.frame()
while(i<=4){
while(n<=10) {
a<-cbind(test[i, 3*n-2], test[i, 3*n-1], test[i,3*n])
b<-rbind(b,a); n<-n+1
} ; i<-i+1; c<-cbind(c,b)
}
Basically what I'm trying to do is to group each line by three columns and
transform it into multiple lines, and then do it to every line and bind
these columns.
My desired output would look like:
1 2 3 31 32 33 61 62 63 81 82 83
4 5 6 34 35 36 64 65 66 84 85 86
7 8 9 37 38 39 67 68 69 ......
10 11 12 40 41 42 ......
13 14 15 43 45 46
16 17 18 ......
19 20 21
22 23 24
25 26 27
28 29 30 58 59 60 78 79 80 118 119 120
However what I have written only work for the first line, apparently the
outer loop doesn't work. What's wrong with it please?

No comments:

Post a Comment