Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cut integer into equally sized integers and assign to vector

Tags:

r

Lets assume the integer x. I want to split this quantity in n mostly equal chunks and save the values in a vector. E.g. if x = 10 and n = 4 then the resulting vector would be:

(3,3,2,2)

and if n = 3:

(4,3,3)

Note: The order of the resulting vector does not matter

like image 555
sigvardsen Avatar asked Mar 26 '17 22:03

sigvardsen


1 Answers

While this will create a (probably unnecessary) large object when x is large, it is still pretty quick:

x <- 10
n <- 4
tabulate(cut(1:x, n))
#[1] 3 2 2 3

On a decent modern machine dividing 10M records into 100K groups, it takes only 5 seconds:

x <- 1e7
n <- 1e5
system.time(tabulate(cut(1:x, n)))
# user  system elapsed 
# 5.07    0.06    5.13 
like image 90
thelatemail Avatar answered Nov 15 '22 15:11

thelatemail