Home > Enterprise >  Create batches of intervals up to a maximum number
Create batches of intervals up to a maximum number

Time:05-19

I am trying to create "batches" of numbers upto a maximum number.

Suppose I have:

max = 3998878

I would like to create batches of 10,000 upto the maximum.

i.e.

c(1, 10000)
c(10001, 20000)
c(20001, 30000)
c(30001, 40000)
...

c(399000, 3998878)

etc.

If I change the maximum to 99879 then the last batch would also be smaller than the other batches c(90000, 99879) (i.e. a size of 9879).

CodePudding user response:

One way, in a dataframe

upr=333
stp=100
    
cbind(
  seq(1,upr,stp),
  c(seq(stp,upr,stp),upr)
)
     [,1] [,2]
[1,]    1  100
[2,]  101  200
[3,]  201  300
[4,]  301  333

In case upr is a multiple of stp, then just put a unique in the second column unique(c(seq(stp,upr,stp),upr)).

CodePudding user response:

Another way, with sequence:

upr = 399
step = 100

c(1, sequence(rep(2, floor(upr / step)), seq(step, upr, step)), upr) |>
  matrix(ncol = 2, byrow = T)

     [,1] [,2]
[1,]    1  100
[2,]  101  200
[3,]  201  300
[4,]  301  399

As @Sotos mentioned in the comments, you might be better off with cut (depending on what you want). Something like:

cut(seq(upr), breaks = c(seq(1, upr, step), upr))

CodePudding user response:

Another option:

upr <- 333
stp <- 100
vec <- c(1:upr)

lapply(split(vec, ceiling(seq_along(vec)/stp)), function(x) x[c(1, length(x))])
# $`1`
# [1]   1 100

# $`2`
# [1] 101 200

# $`3`
# [1] 201 300

# $`4`
# [1] 301 333
  •  Tags:  
  • r
  • Related