countsasretainretaincount

SAS Retain & Count Statements by Groups


I'm a newbie to SAS and would like to have your help on my codes. I'm working on retain statement to count on the patients visits to different clinics within a month.

My original dataset is a long file (per person per visit).

ID VisitCode
121 4
122 3
123 6
123 4
125 2
125 5
127 1
127 1
127 5
127 5

I'l like to have a wide file in the end that I can see the number of visits a patient to different clinics. Like this:

ID CtC1Visit CtC2Visit CtC3Visit CtC4Visit CtC5Visit CtC6Visit
121 0 0 0 1 0 0
122 0 0 1 0 0 0
123 0 0 0 1 0 1
125 0 1 0 0 1 0
127 2 0 0 0 2 0

Here are my codes. Somehow the people with multiple records of clinic visits just went missing.

data L3; set L3; BY ID;
retain CtC1Visit CtC1Visit CtC2Visit CtC3Visit CtC4Visit CtC6Visit;
if first.id then do;
  CtC1Visit=0;
  CtC2Visit=0;
  CtC3Visit=0;
  CtC4Visit=0;
  CtC5Visit=0;
  CtC6Visit=0;
end;
if VisitCode=1 then CtC1Visit=CtC1Visit+1;
if VisitCode=2 then CtC2Visit=CtC2Visit+1;
if VisitCode=3 then CtC3Visit=CtC3Visit+1;
if VisitCode=4 then CtC4Visit=CtC4Visit+1;
if VisitCode=5 then CtC5Visit=CtC5Visit+1;
if VisitCode=6 then CtC6Visit=CtC6Visit+1;
if last.ID then output;
run;

Result of My Current Codes

ID CtC1Visit CtC2Visit CtC3Visit CtC4Visit CtC5Visit CtC6Visit
121 0 0 0 1 0 0
122 0 0 1 0 0 0
123 . . . . . .
125 . . . . . .
127 . . . . . .

Solution

  • Welcome and kudos to asking a clear question with desired result posted.

    data have;
    input ID VisitCode;
    datalines;
    121 4
    122 3
    123 6
    123 4
    125 2
    125 5
    127 1
    127 1
    127 5
    127 5
    ;
    
    data want;
       set have;
       by ID;
       array ct{*} CtVisitC1 - CtVisitC6 (6*0);
       if first.ID then call stdize('replace', 'mult=', 0, of ct[*], _N_);
       ct[VisitCode] + 1;
       if last.ID;
       drop VisitCode;
    run;