仅在按组时输出变量

时间:2017-06-13 16:56:29

标签: sas

我的第一次发帖。我对SAS编程很新(实际上都是编程)。这似乎是一个简单的问题,但无法弄清楚。我有一些交叉表输出,我正在努力使其成形以便于输出到表格。如果该组中只有3个观察结果,我想保留按组的第一个观察结果。如果有超过3个观测值,我想保留所有观测值,但最后一个。所以,例如,这就是我所拥有的:

private void unlockFocus() {
    try {
        // Reset the auto-focus trigger
        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
        setAutoFlash(mPreviewRequestBuilder);
/*HERE*/ mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
                mBackgroundHandler);
        // After this, the camera will go back to the normal state of preview.
        mState = STATE_PREVIEW;
        mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback,
                mBackgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

这就是我想要的新数据集

Group1  Group2  Percent
var1    1   0.25
var1    1   0.75
var1    1   1
var1    2   0.4
var1    2   0.6
var1    2   1
var1    3   0.7
var1    3   0.3
var1    3   0.6
var2    1   0.1
var2    1   0.2
var2    1   0.4
var2    1   0.3
var2    1   1
var2    2   0.2
var2    2   0.2
var2    2   0.2
var2    2   0.2
var2    2   1
var2    3   0.7
var2    3   0.1
var2    3   0.05
var2    3   0.05
var2    3   0.1

希望这很清楚,但如果需要更多信息,请告诉我。

1 个答案:

答案 0 :(得分:0)

我已经通过几个步骤将其分解,以帮助您查看逻辑并使用了数据步骤和SQL。基本上你想要计算每组中有多少并保持所有计数(组内的计数和总计数),这样你就可以用它们来制作你的最终逻辑。

data test;
    length GROUP1 $5 GROUP2 PERCENT 8;
    input GROUP1 $ GROUP2 PERCENT;
    datalines;
    var1    1   0.25
    var1    1   0.75
    var1    1   1
    var1    2   0.4
    var1    2   0.6
    var1    2   1
    var1    3   0.7
    var1    3   0.3
    var1    3   0.6
    var2    1   0.1
    var2    1   0.2
    var2    1   0.4
    var2    1   0.3
    var2    1   1
    var2    2   0.2
    var2    2   0.2
    var2    2   0.2
    var2    2   0.2
    var2    2   1
    var2    3   0.7
    var2    3   0.1
    var2    3   0.05
    var2    3   0.05
    var2    3   0.1 
    ;
run;

** count the number of obs per group **;
data test_ct; set test;
    by GROUP1 GROUP2;
    COUNT + 1;
    if first.GROUP2 then COUNT = 1;
run;

** count the total number of obs per group and output on each row **;
proc sql noprint;
    create table test_ct_all as
    select *, count(*) as COUNT_TOTAL
    from test_ct group by GROUP1,GROUP2
    order by GROUP1, GROUP2, COUNT;
quit;

** logic to keep records **;
data keep_flags; set test_ct_all;
    if COUNT=1 and COUNT_TOTAL=3 then KEEP=1;

    *the last record will have COUNT and COUNT_TOTAL equal;
    if COUNT_TOTAL > 3 and (COUNT_TOTAL ne COUNT) then KEEP=1;
run;

** output only the keep records **;
data keepers; set keep_flags;
    if KEEP=1;
run;