Understand the my_breaks function

We have the following function:

my_breaks <-function(x, h = 5) {
  x <- sort(x)
  breaks <- xb <- x[1]
  k <- 1
  for(i in seq_along(x)[-1]){
    if(k<h) {
      k <- k+1
    } else {
      if(xb<x[i-1]&&x[i-1]<x[i]){
        xb <- x[i-1]
        breaks <-c(breaks, xb)
        k <- 1
      }
    }
  }
  breaks
}

To help you understand it better, I’ll try to break it down into iterations. Let’s start with the starting vector as it is x = c(rep(1,4),1:5,8:10, rep(10,4)). That is, x = [1, 1, 1, 1, 1, 2, 3, 4, 5, 8, 9, 10, 10, 10, 10, 10]

x=c(rep(1,4),1:5,8:10, rep(10,4))

Now let’s call the my_breaks function with the parameter h = 3 that is `my_breaks(c(rep(1,4),1:5,8:10, rep(10,4)), 3)`.

You will observe what happens to the individual variables in the main for loop.

Note such a notation i in seq_along (x) [- 1] causes that the variable i will be iterated by the values 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16.

Please analyze carefully and carefully what happens in subsequent iterations.

In the table below you will find a detailed list of each of them. Note that I marked each change in the value of the variable by bold its value.

i k x[i] x[i-1] xb breask coment
- 1 1 1 after breaks <- xb <- x[1] and k <- 1
2 2 1 1 1 1 k<h==T
3 3 1 1 1 1 k<h==T
4 3 1 1 1 1 k<h==F and xb<x[i-1]&&x[i-1]<x[i]==F
5 3 1 1 1 1 k<h==F and xb<x[i-1]&&x[i-1]<x[i]==F
6 3 2 1 1 1 k<h==F and xb<x[i-1]&&x[i-1]<x[i]==F
7 1 3 2 2 (1, 2) k<h==F and xb<x[i-1]&&x[i-1]<x[i]==T
8 2 4 3 2 (1, 2) k<h==TRUE
9 3 5 4 2 (1, 2) k<h==TRUE
10 1 8 5 5 (1, 2, 5) k<h==F and xb<x[i-1]&&x[i-1]<x[i]==T
11 2 9 8 5 (1, 2, 5) k<h==TRUE
12 3 10 9 5 (1, 2, 5) k<h==TRUE
13 3 10 10 5 (1, 2, 5) k<h==F and xb<x[i-1]&&x[i-1]<x[i]==F
14 3 10 10 5 (1, 2, 5) k<h==F and xb<x[i-1]&&x[i-1]<x[i]==F
15 3 10 10 5 (1, 2, 5) k<h==F and xb<x[i-1]&&x[i-1]<x[i]==F
16 3 10 10 5 (1, 2, 5) k<h==F and xb<x[i-1]&&x[i-1]<x[i]==F

After calling our my_breaks function, we get the following result:

my_breaks(x, 3)
## [1] 1 2 5