Takes a sample from a given range (for example, 1 to 100), and a specified resulting vector length (for example, 10), which add up to a specified value.

SampleToSum(
  Target = 100,
  VecLen = 10,
  InRange = 1:100,
  Tolerance = 2,
  showSum = TRUE
)

Arguments

Target

The value that the vector should sum to

VecLen

The required vector length

InRange

The input range that values can be sampled from

Tolerance

A "buffer" for the Target argument, allowing the resulting sum to be slightly higher or slightly lower than specified.

showSum

Logical. Should the resulting total be shown?

Value

A vector

Note

There is a good chance that with certain settings, this will be VERY SLOW!

References

http://stackoverflow.com/a/14687223/1270695

Author

Ananda Mahto

Examples

set.seed(1) SampleToSum()
#> Total = 101
#> [1] 20 6 11 20 6 3 24 1 4 6
SampleToSum()
#> Total = 99
#> [1] 6 11 3 18 11 19 3 5 22 1
SampleToSum(Tolerance = 0)
#> Total = 100
#> [1] 19 15 4 10 1 11 7 16 4 13
SampleToSum(Tolerance = 0)
#> Total = 100
#> [1] 11 30 12 2 9 8 6 1 3 18
set.seed(123) ## You'll have to wait a few seconds here SampleToSum(Target = 1163, VecLen = 15, InRange = 50:150)
#> Total = 1162
#> [1] 52 134 128 58 71 97 70 78 60 95 66 67 55 50 81