2

I'm trying to create a function that will spread a number into an X number of groups that are approximately equal. For example, splitting 32 into 3 separate groups would result in 11, 11, and 10. Splitting 32 into 5 separate groups would result in 7, 7, 6, 6, 6.

I've found a lot of Python approaches, and I've found lots of R approaches that split samples. But, I haven't found any R specific approaches that focus on splitting a specific count rather than a sample.

Any help would be much appreciated!

Trent
  • 771
  • 5
  • 19

3 Answers3

3

A transcription of a python code provided by @Poe Dator:

int_split <- function(n, p) n %/% p + (sequence(p) - 1 < n %% p)

int_split(32, 3)

[1] 11 11 10

int_split(32, 5)

[1] 7 7 6 6 6
tmfmnk
  • 38,881
  • 4
  • 47
  • 67
1

You could do:

split_count <- function(x, n){
  grp <- rep(x%/%n, n)
  y <- x%%n
  grp[seq_len(y)] <- grp[seq_len(y)] + 1
  grp
}

split_count(32, 2)
[1] 16 16
split_count(32, 5)
[1] 7 7 6 6 6
 split_count(32, 3)
[1] 11 11 10
Onyambu
  • 67,392
  • 3
  • 24
  • 53
1

Here's a "Monte Carlo" approach. I generate a bunch (N) of random integers (size = grps) that sum to Num and then choose the combination with the least difference.

Num <- 32
grps <- 4
N <- 1000

tmp <- rmultinom(N,Num,rep(1/grps,grps))
i <- which.min(apply(tmp,2,function(x) sum(abs(diff(x)))))
tmp[,i]
Brian Davis
  • 990
  • 5
  • 11