Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All combinations of values between 0-1 sum to 1 in R

Tags:

r

Simple question: I'm trying to get all combinations where the weights of 3 numbers (between 0.1 and 0.9) sums to 1.

Example:

c(0.20,0.20,0.60)
c(0.35,0.15,0.50)
.................

with weights differing by 0.05

I have tried this:

library(gregmisc)
permutations(n = 9, r = 3, v = seq(0.1,0.9,0.05))

combn(seq(0.1,0.9,0.05),c(3))

However I would need the 3 numbers (weights) to equal 1, how can I do this?

like image 942
Maximilian Avatar asked Oct 13 '13 11:10

Maximilian


1 Answers

x <- expand.grid(seq(0.1,1,0.05),
                 seq(0.1,1,0.05),
                 seq(0.1,1,0.05))

x <- x[rowSums(x)==1,]

Edit: Use this instead to avoid floating point errors:

x <- x[abs(rowSums(x)-1) < .Machine$double.eps ^ 0.5,]

#if order doesn't matter
unique(apply(x,1,sort), MARGIN=2)
#      15   33  51   69  87  105 123  141  393  411  429  447  465  483 771  789 807  825 #843 1149 1167 1185 1527 1545
#[1,] 0.1 0.10 0.1 0.10 0.1 0.10 0.1 0.10 0.15 0.15 0.15 0.15 0.15 0.15 0.2 0.20 0.2 0.20 0.2 0.25 0.25 0.25  0.3 0.30
#[2,] 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.15 0.20 0.25 0.30 0.35 0.40 0.2 0.25 0.3 0.35 0.4 0.25 0.30 0.35  0.3 0.35
#[3,] 0.8 0.75 0.7 0.65 0.6 0.55 0.5 0.45 0.70 0.65 0.60 0.55 0.50 0.45 0.6 0.55 0.5 0.45 0.4 0.50 0.45 0.40  0.4 0.35

This will run into performance and memory problems if the possible number of combinations gets huge.

like image 68
Roland Avatar answered Oct 30 '22 13:10

Roland