Vector whose elements add up to a value in R -
i'm trying create vector elements add specific number. example, let's want create vector 4 elements, , must add 20, elements 6, 6, 4, 4 or 2, 5, 7, 6, whatever. tried run lines using sample() , seq() cannot it.
any appreciated.
to divide 4 parts, need 3 breakpoints 19 possible breaks between 20 numbers. partitions sizes of intervals between 0, partitions, , 20:
> sort(sample(19,3)) [1] 5 7 12 > diff(c(0, 5,7,12,20)) [1] 5 2 5 8 test, lets create big matrix of them. each column instance:
> trials = sapply(1:1000, function(x){diff(c(0,sort(sample(19,3)),20))}) > trials[,1:6] [,1] [,2] [,3] [,4] [,5] [,6] [1,] 3 1 8 13 3 2 [2,] 4 7 10 2 9 5 [3,] 2 11 1 4 3 7 [4,] 11 1 1 1 5 6 do add 20?
> all(apply(trials,2,sum)==20) [1] true are there weird cases?
> range(trials) [1] 1 17 no, there no zeroes , nothing bigger 17, (1,1,1,17) case. can't have 18 without zero.
Comments
Post a Comment