r - Filtering permutations to avoid running out of memory -


the context of problem asset allocation. if have n assets, , can allocate them in 5% chunks, permutations exist such sum of allocation equal 100%.

for example if had 2 assets there 21 (created using function "fmakeallocationsweb(2)" code @ bottom of post:

      [,1] [,2]  [1,]    0  100  [2,]    5   95  [3,]   10   90  [4,]   15   85  [5,]   20   80  [6,]   25   75  [7,]   30   70  [8,]   35   65  [9,]   40   60 [10,]   45   55 [11,]   50   50 [12,]   55   45 [13,]   60   40 [14,]   65   35 [15,]   70   30 [16,]   75   25 [17,]   80   20 [18,]   85   15 [19,]   90   10 [20,]   95    5 [21,]  100    0 

the problem of course come when number of assets increases, modestly. understandable repetition number of permutations n^(n) , i'm not able allocate intermediate step of creating permutations memory. example 20 assets number of permutations 5.84258701838598e+27!!

i able filter these on fly (sum==100) not run memory allocation issue. digging code beneath gtools::permutations seems vectorised , intervening there filter seems impossible.

would gratefully welcome thoughts - ideally prefer stick r code , packages.

many thanks

russ

installifmissing <- function(spackagename) {   if (!spackagename %in% installed.packages()) install.packages(spackagename) }   fmakeallocationsweb<-function(inumassets=10,iincrement=5){ installifmissing("gtools") require(gtools)  ialloc<-seq(0,100,by=iincrement) #'the allocation increments eg 0,5,10...,95,100 #'generate permutations permut<-permutations(n=length(ialloc),r=inumassets,v=ialloc,repeats.allowed=true) #'filter permuatations sum 100' permutsum<-apply(permut,margin=1,fun=sum) permut100<-permut[which(permutsum==100),] return(permut100) } 

if install partitions package, have restrictedparts function enumerate ways can add n numbers sum s. in case, want restrict summands multiples of 5, , restriction add s=100. instead, divide summands 5 , have total add 20. if want 2 assets, code restrictedparts(100/5,2) * 5 give 10 unordered pairs.

you can loop through columns , enumerate, each, set of permutations of asset allocations. you'll have deal case there repeated elements - example, generate {100,0} represents <100,0> , <0,100> whereas {50,50} represents single allocation <50,50>. can deal using set attribute of permuatations

restrictedparts(100/5,20) * 5 gives 627 partitions add 100% - , you'll need permute each of these full list of allocations.


Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -