I am trying to use the variable PERIOD as an iterator for the period_array. However the iterator does not seem to be working. If I change period_array(PERIOD) to a fixed value location like period_array(3) then it correctly places a value at position 3. Can someone tell me where I am going wrong?
I have been using this as the template: https://stats.idre.ucla.edu/sas/modules/reshaping-data-long-to-wide-using-the-data-step/
Any assistance would be greatly appreciated,
Input dataset:
PATH | PERIOD | RATE |
1 | 1 | 5 |
1 | 2 | 7 |
1 | 3 | 3 |
2 | 1 | 1 |
2 | 2 | 2 |
2 | 3 | 2 |
SAS CODE:
DATA WORK.LMM_Paths;
SET WORK.LMM_PATHS_IN;
BY PATH;
ARRAY PERIOD_ARRAY(3) PERIOD1-PERIOD3;
IF first.PATH THEN DO;
DO i=1 to 3;
period_array{i}=.;
END;
END;
period_array(PERIOD)=RATE;
IF last.PATH THEN OUTPUT;
RUN;
Output dataset:
PATH | PERIOD | RATE | PERIOD1 | PERIOD2 | PERIOD3 |
1 | 360 | 5 | . | . | . |
retain the array:
DATA WORK.LMM_Paths;
SET WORK.LMM_PATHS_IN;
BY PATH;
ARRAY PERIOD_ARRAY(3) PERIOD1-PERIOD3;
retain period_array; /*retain the array*/
IF first.PATH THEN DO;
DO i=1 to 3;
period_array{i}=.;
END;
END;
period_array(PERIOD)=RATE;
IF last.PATH THEN OUTPUT;
RUN;
retain the array:
DATA WORK.LMM_Paths;
SET WORK.LMM_PATHS_IN;
BY PATH;
ARRAY PERIOD_ARRAY(3) PERIOD1-PERIOD3;
retain period_array; /*retain the array*/
IF first.PATH THEN DO;
DO i=1 to 3;
period_array{i}=.;
END;
END;
period_array(PERIOD)=RATE;
IF last.PATH THEN OUTPUT;
RUN;
Ah of course!
I see my original code was reinitializing the array at the end of the data step!
Thank you.
@novinosrin wrote:
retain the array:
DATA WORK.LMM_Paths; SET WORK.LMM_PATHS_IN; BY PATH; ARRAY PERIOD_ARRAY(3) PERIOD1-PERIOD3; retain period_array; /*retain the array*/ IF first.PATH THEN DO; DO i=1 to 3; period_array{i}=.; END; END; period_array(PERIOD)=RATE; IF last.PATH THEN OUTPUT; RUN;
Consider using DO UNTIL(LAST.PATH) with SET in the loop. This will allow you to remove the RETAIN and let SAS initialize to missing the elements of the array.
data work.lmm_paths;
do until(last.path);
set work.lmm_paths_in;
by path;
array period_array[3] period1-period3;
period_array[period]=rate;
end;
run;
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.