ポートフォリオウェイトの全組み合わせを返す関数

投資可能領域を描画する時等、ポートフォリオウェイトの可能な全ての組み合わせのが欲しい場合があるのでそれを返す関数を作成した。

combination.constantsum <- function(num,val.step,val.current=1)
{
    if(num==1){
        return(val.current)
    }
    result <- NULL
    for(x in seq(0,val.current,val.step)){
        result <- rbind(result,cbind(x,combination.constantsum(num-1,val.step,val.current-x)))
    }
    return(result)
}

使用方法は資産数をnum、何%ごとのウェイトで計算するかをval.stepに入れればOK。

>combination.constantsum(2,0.2)
       x    
[1,] 0.0 1.0
[2,] 0.2 0.8
[3,] 0.4 0.6
[4,] 0.6 0.4
[5,] 0.8 0.2
[6,] 1.0 0.0
> combination.constantsum(3,0.1)
        x   x    
 [1,] 0.0 0.0 1.0
 [2,] 0.0 0.1 0.9
 [3,] 0.0 0.2 0.8
 [4,] 0.0 0.3 0.7
 [5,] 0.0 0.4 0.6
 [6,] 0.0 0.5 0.5
 [7,] 0.0 0.6 0.4
 [8,] 0.0 0.7 0.3
 [9,] 0.0 0.8 0.2
[10,] 0.0 0.9 0.1
[11,] 0.0 1.0 0.0
[12,] 0.1 0.0 0.9
[13,] 0.1 0.1 0.8
[14,] 0.1 0.2 0.7
[15,] 0.1 0.3 0.6
[16,] 0.1 0.4 0.5
[17,] 0.1 0.5 0.4
[18,] 0.1 0.6 0.3
[19,] 0.1 0.7 0.2
[20,] 0.1 0.8 0.1
[21,] 0.1 0.9 0.0
[22,] 0.2 0.0 0.8
[23,] 0.2 0.1 0.7
[24,] 0.2 0.2 0.6
[25,] 0.2 0.3 0.5
[26,] 0.2 0.4 0.4
[27,] 0.2 0.5 0.3
[28,] 0.2 0.6 0.2
[29,] 0.2 0.7 0.1
[30,] 0.2 0.8 0.0
[31,] 0.3 0.0 0.7
[32,] 0.3 0.1 0.6
[33,] 0.3 0.2 0.5
[34,] 0.3 0.3 0.4
[35,] 0.3 0.4 0.3
[36,] 0.3 0.5 0.2
[37,] 0.3 0.6 0.1
[38,] 0.3 0.7 0.0
[39,] 0.4 0.0 0.6
[40,] 0.4 0.1 0.5
[41,] 0.4 0.2 0.4
[42,] 0.4 0.3 0.3
[43,] 0.4 0.4 0.2
[44,] 0.4 0.5 0.1
[45,] 0.4 0.6 0.0
[46,] 0.5 0.0 0.5
[47,] 0.5 0.1 0.4
[48,] 0.5 0.2 0.3
[49,] 0.5 0.3 0.2
[50,] 0.5 0.4 0.1
[51,] 0.5 0.5 0.0
[52,] 0.6 0.0 0.4
[53,] 0.6 0.1 0.3
[54,] 0.6 0.2 0.2
[55,] 0.6 0.3 0.1
[56,] 0.6 0.4 0.0
[57,] 0.7 0.0 0.3
[58,] 0.7 0.1 0.2
[59,] 0.7 0.2 0.1
[60,] 0.7 0.3 0.0
[61,] 0.8 0.0 0.2
[62,] 0.8 0.1 0.1
[63,] 0.8 0.2 0.0
[64,] 0.9 0.0 0.1
[65,] 0.9 0.1 0.0
[66,] 1.0 0.0 0.0

ちなみにval.current=2とかすると、合計が1ではなく、2になるような全ての組み合わせを返却する。