This script first generates a test dataset (wbh) containing simulated age and race combinations via nested loops. It then performs advanced transformation in a DATA step using an ARRAY and the RETAIN statement to manipulate data horizontally (pivot type) and calculate sums, with variables reset upon age group change.
Data Analysis
Type : CREATION_INTERNE
Data is entirely generated by the code via nested DO loops; no external source is required.
1 Code Block
DATA STEP Data
Explanation : Creation of the 'wbh' dataset through simulation. Two nested loops generate observations for 10 ages and 8 races, calculating a variable 'n' as the product of the two.
Copied!
data wbh;
do age=1 to 10;
do race=1 to 8;
n=age*race;
output;
end;
end;
run;
1
DATA wbh;
2
DO age=1 to 10;
3
DO race=1 to 8;
4
n=age*race;
5
OUTPUT;
6
END;
7
END;
8
RUN;
2 Code Block
PROC PRINT
Explanation : Display of the content of the previously generated 'wbh' table.
Copied!
proc print;run;
1
PROC PRINT;RUN;
3 Code Block
DATA STEP Data
Explanation : Data transformation. Use of an array 'a' (variables m1-m8) with RETAIN to preserve values between iterations. The 'do i=1 to 8' loop resets values to missing (.) at the beginning of each age group (first.age). The value 'n' is assigned to the index corresponding to 'race', and a total sum 'totn' is calculated.
Copied!
data test; set wbh; by age race;
array a(8) m1-m8;
retain m1-m8;
do i=1 to 8;
if first.age then do;
a(i)=.;
end;
end;
a(race)=n;
totn=sum(of m1-m8);
run;
1
DATA test; SET wbh; BY age race;
2
array a(8) m1-m8;
3
retain m1-m8;
4
DO i=1 to 8;
5
IF first.age THENDO;
6
a(i)=.;
7
END;
8
END;
9
10
a(race)=n;
11
totn=sum(of m1-m8);
12
RUN;
4 Code Block
PROC PRINT
Explanation : Display of the final result contained in the 'test' table.
Copied!
proc print;run;
1
PROC PRINT;RUN;
This material is provided "as is" by We Are Cas. There are no warranties, expressed or implied, as to merchantability or fitness for a particular purpose regarding the materials or code contained herein. We Are Cas is not responsible for errors in this material as it now exists or will exist, nor does We Are Cas provide technical support for it.
SAS and all other SAS Institute Inc. product or service names are registered trademarks or trademarks of SAS Institute Inc. in the USA and other countries. ® indicates USA registration. WeAreCAS is an independent community site and is not affiliated with SAS Institute Inc.
This site uses technical and analytical cookies to improve your experience.
Read more.