Trent
Trent

Reputation: 803

Creating a function to split single number in approximately equal groups R

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!

Upvotes: 2

Views: 460

Answers (3)

Brian Davis
Brian Davis

Reputation: 992

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]

Upvotes: 1

tmfmnk
tmfmnk

Reputation: 39858

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

Upvotes: 4

Onyambu
Onyambu

Reputation: 79228

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

Upvotes: 1

Related Questions