I need to create a function (in R) which:
– given N possible variables to attribute weights to;
– creates all possible permuations of weights (summing to 100%);
– subject to the constraint that weights must occur in multiples of P (usually 1%)
Obviously, as N and P are inversely related – i.e. I can’t specify N=7, and P=0.4. However, I’d like to be able to specify integer solutions only, i.e. P=0.01.
Sorry if this is a well-known problem – I’m not a math person, and I’ve searched using terms I know, but didn’t find anything close enough.
I’d post the code I’ve written, but.. it’s not impressive or insightful.
Thanks for any help!
Assuming the order of the weights matters, these are compositions; if they don’t then these are partitions. In either case, they are restricted by the number of parts, what you have called N, though the code which follows uses
numparts. There is also the question of whether weights of 0 are allowed.Since you want weights to add up to 1, you need 1/p to be an integer, which in the following code is
sumparts; it does not depend on the number of weights. Once you have the compositions, you can multiply them by p, i.e. divide byn, to get your weights.R has a
partitionspackage to generate such compositions or restricted partitions. The following code should be self explanatory: each column in the matrix is a set of weights. I have taken seven weights and p=0.1 or 10%, and prohibited weights of 0: this gives 84 possibilities; allowing weights of 0 would mean 8008 possibilities. With p=0.01 or 1% there would be 1,120,529,256 possibilities without weights of 0, and 1,705,904,746 with. If order does not matter, userestrictedpartsinstead ofcompositions.