If I want to sample numbers to create a vector I do:
set.seed(123)
x <- sample(1:100,200, replace = TRUE)
sum(x)
# [1] 10228
What if I want to sample 20 random numbers that sum to 100, and then 30 numbers but still sum to 100. This I imagine will be more of a challenge than it seems. ?sample and searching Google has not provided me with a clue. And a loop to sample then reject if not close enough( e.g. within 5) of the desired sum I guess may take some time.
Is there a better way to achieve this?
an example would be:
foo(10,100) # ten random numbers that sum to 100. (not including zeros)
# 10,10,20,7,8,9,4,10,2,20
Here’s another attempt. It doesn’t use
sample, but usesrunif. I’ve added an optional “message” to the output showing the sum, which can be triggered using theshowSumargument. There is also aToleranceargument that specifies how close to the target is required.Here are some examples.
Notice the difference between the default setting and setting
Tolerance = 0You can verify this behavior by using
replicate. Here’s the result of settingTolerance = 0and running the function 5 times.And the same for setting
Tolerance = 5and running the function 5 times.Not surprisingly, setting the tolerance to 0 would make the function slower.
Speed (Or lack thereof)
Note that since this is a “random” process, it’s hard to guess how long it would take to find the right combination of numbers. For example, using
set.seed(123), I ran the following test three times in a row:The first run took just over 9 seconds. The second took just over 7.5 seconds. The third took… just under 381 seconds! That’s a lot of variation!
Out of curiosity, I added a counter into the function, and the first run took 55026 attempts to arrive at a vector that satisfied all of our conditions! (I didn’t bother trying for the second and third attempts.)
It might be good to add some error or sanity checking into the function to make sure the inputs are reasonable. For example, one should not be able to enter
SampleToSum(Target = 100, VecLen = 10, InRange = 15:50)since with a range of 15 to 50, there’s no way to get to 100 AND have 10 values in your vector.