Home > Software engineering >  How to consecutively subset an array and count the number of iterations?
How to consecutively subset an array and count the number of iterations?

Time:06-24

I need to repeatedly apply a function on the resultant arrays until all data in the array is reduced to a single set, and count the number of iterations.

Data Array ar

structure(c(0, 11, 17, 15, 22, 67, 73, 68, 31, 31, 28, 33, 34, 
32, 11, 0, 9, 12, 21, 67, 73, 67, 35, 30, 34, 67, 60, 36, 17, 
9, 0, 6, 19, 70, 74, 68, 36, 36, 36, 64, 66, 39, 15, 12, 6, 0, 
13, 64, 69, 66, 34, 37, 39, 77, 65, 45, 22, 21, 19, 13, 0, 59, 
60, 66, 38, 39, 39, 40, 43, 43, 67, 67, 70, 64, 59, 0, 10, 18, 
77, 75, 78, 93, 93, 85, 73, 73, 74, 69, 60, 10, 0, 15, 76, 74, 
80, 103, 101, 95, 68, 67, 68, 66, 66, 18, 15, 0, 59, 65, 73, 
90, 87, 82, 31, 35, 36, 34, 38, 77, 76, 59, 0, 8, 19, 24, 28, 
32, 31, 30, 36, 37, 39, 75, 74, 65, 8, 0, 12, 20, 22, 23, 28, 
34, 36, 39, 39, 78, 80, 73, 19, 12, 0, 6, 14, 18, 33, 67, 64, 
77, 40, 93, 103, 90, 24, 20, 6, 0, 2, 8, 34, 60, 66, 65, 43, 
93, 101, 87, 28, 22, 14, 2, 0, 6, 32, 36, 39, 45, 43, 85, 95, 
82, 32, 23, 18, 8, 6, 0), .Dim = c(14L, 14L))

From

a<-colSums(ar<25)
b<-which.max(a)
c<-ar[ar[,b] > 25,, drop = FALSE]

we get

structure(c(0, 11, 17, 15, 22, 67, 73, 68, 11, 0, 9, 12, 21, 
67, 73, 67, 17, 9, 0, 6, 19, 70, 74, 68, 15, 12, 6, 0, 13, 64, 
69, 66, 22, 21, 19, 13, 0, 59, 60, 66, 67, 67, 70, 64, 59, 0, 
10, 18, 73, 73, 74, 69, 60, 10, 0, 15, 68, 67, 68, 66, 66, 18, 
15, 0, 31, 35, 36, 34, 38, 77, 76, 59, 31, 30, 36, 37, 39, 75, 
74, 65, 28, 34, 36, 39, 39, 78, 80, 73, 33, 67, 64, 77, 40, 93, 
103, 90, 34, 60, 66, 65, 43, 93, 101, 87, 32, 36, 39, 45, 43, 
85, 95, 82), .Dim = c(8L, 14L))

then from

a<-colSums(c<25)
b<-which.max(a)
d<-c[c[,b]>25,,drop=FALSE]

we get

structure(c(67, 73, 68, 67, 73, 67, 70, 74, 68, 64, 69, 66, 59, 
60, 66, 0, 10, 18, 10, 0, 15, 18, 15, 0, 77, 76, 59, 75, 74, 
65, 78, 80, 73, 93, 103, 90, 93, 101, 87, 85, 95, 82), .Dim = c(3L, 
14L))

applying once more

a<-colSums(d<25)
b<-which.max(a)
e<-d[d[,b]>25,,drop=FALSE]

results in a array with no values

structure(numeric(0), .Dim = c(0L, 14L))

Then, the operation can be performed a number of times, and I need to know how many times; in this case it was 3 times. Also, I need to reduce the number of the lines of the code probably with a loop function, as the action is repetitive.

CodePudding user response:

You can use recursion as shown below:

fun<- function(x, i=1){
    a<-which.max(colSums(x<25)) 
    b<-x[x[,a] > 25,, drop = FALSE]
    if(length(b)) Recall(b, i 1) else i
}

fun(ar)
[1] 3
  • Related