SAS

时间:2018-04-30 11:09:41

标签: sas

所以我有这个代码,旨在根据原有的成熟度加入新的利率。例如,如果原始到期日为0.25年,我希望它附加3个月利率的利率。

代码看起来像

data want;
set maturity;

retain tempMat tempRate;
i = 1;
do until(stop eq 1);
    set Maturity2 nobs = num point = i;
    diff = abs(sum(Maturity, -OriginalMaturity));
    if i eq 1 then
    do;
        tempMat = diff;
        tempRate = Base_Rate_New;
    end;
    else
    do;
        if i = num then
        do;
            stop = 1;
            Rate_ok = Base_Rate_New;
        end;
        else if diff gt tempMat then
        do;
            stop = 1;
            Rate_ok = tempRate;
        end;
        else
        do;
            tempMat = diff;
            tempRate = Base_Rate_New;
        end;
    end;
    i = i + 1;
end;

端; 跑;

这两个表看起来像

data maturity;
input ID maturity base_rate;
datalines
1 0.25 1
2 0.5 1
3 0.6 2
4 0.3 3
5 1.2 1.2
6 1.5 2
7 2 3
8 3 1
9 1 0.5
;

data maturity2;
input originalmaturity base_rate_new;
datalines
0.25 2
0.5 3
0.75 1
1 3
;
run;

我想要创建的数据集看起来像(在删除所有额外变量之后

data want;
input ID maturity base_rate base_rate_new;
datalines
1 0.25 1 2
2 0.5 1 3
3 0.6 2 3
4 0.3 3 2
5 1.2 1.2 3
6 1.5 2 3
7 2 3 3
8 3 1 3
9 1 0.5 3
;
run;

问题是,如果值超过更接近的数字,它仍然选择更高的数字。例如,如果它是0.3,它将选择0.5而不是0.25

2 个答案:

答案 0 :(得分:1)

假设第二个数据集按升序排序,那么您需要找到围绕该值的2个速率并检查哪个更接近。您必须处理完全匹配的边缘情况,或者当您到达第二个数据集的末尾时。

/*This assumes maturity2 is sorted ascending by originalmaturity*/
data want(keep=ID maturity originalmaturity base_rate base_rate_new);
set maturity;
stop = 0;
i = 1;

do until(stop eq 1);
    set Maturity2 nobs = num point = i;
/*  put _all_;*/
    if originalmaturity = maturity then do;
        output;
        stop = 1;
    end;

    else if originalmaturity < maturity then do;
        ldist = abs(originalmaturity - maturity);
        lbrn = base_rate_new;
    end;
    else if originalmaturity > maturity then do;
        hdist = abs(originalmaturity - maturity);
        if hdist > ldist then
            base_rate_new = lbrn;
        output;
        stop = 1;
    end;

    if num = i then do;
        output;
        stop = 1;
    end;
    i = i + 1;
end;
run;

答案 1 :(得分:1)

data want;
    set maturity;
    retain tempDiff Rate;
    do point=1 to n;
       set maturity2 nobs=n point=point;
       diff=abs(maturity-originalmaturity);
       if point=1 then do;
            tempDiff=diff;
            Rate=base_rate_new;
       end;
       else if diff<tempDiff then do;
           tempDiff=diff; 
           Rate=base_rate_new;
       end;
    end;
    drop diff tempDiff originalmaturity base_rate_new;
run;