I have a hypothetical table as below. All the years (2012 to 2016) have two types of data (number of members attended, and the total number of member in 6 States)
data have;
input year type $ NY CA PA FL NC AZ;
datalines;
2012 attended 25 33 42 57 68 34
2012 total 200 250 300 240 300 250
2013 attended 35 43 52 67 78 64
2013 total 210 270 330 290 320 280
2014 attended 45 53 6 77 88 54
2014 total 230 270 320 260 310 270
2015 attended 55 63 72 87 98 74
2015 total 260 300 300 290 360 290
2016 attended 65 73 82 97 88 64
2016 total 300 320 330 300 350 320
;
run;
I would like to add a row after each pair of rows with same year. These rows will have percentage of total attended in each state.
data have; input year type $ NY CA ; datalines; 2012 attended 25 33 42 57 68 34 2012 total 200 250 300 240 300 250 2013 attended 35 43 52 67 78 64 2013 total 210 270 330 290 320 280 2014 attended 45 53 6 77 88 54 2014 total 230 270 320 260 310 270 2015 attended 55 63 72 87 98 74 2015 total 260 300 300 290 360 290 2016 attended 65 73 82 97 88 64 2016 total 300 320 330 300 350 320 ; run; data want; set have; by year; lag_NY=lag(NY); lag_CA=lag(CA); output; if last.year then do; type='Percent'; NY=lag_NY/NY; CA=lag_CA/CA; output; end; drop lag_:; run;
data have; input year type $ NY CA ; datalines; 2012 attended 25 33 42 57 68 34 2012 total 200 250 300 240 300 250 2013 attended 35 43 52 67 78 64 2013 total 210 270 330 290 320 280 2014 attended 45 53 6 77 88 54 2014 total 230 270 320 260 310 270 2015 attended 55 63 72 87 98 74 2015 total 260 300 300 290 360 290 2016 attended 65 73 82 97 88 64 2016 total 300 320 330 300 350 320 ; run; data want; set have; by year; lag_NY=lag(NY); lag_CA=lag(CA); output; if last.year then do; type='Percent'; NY=lag_NY/NY; CA=lag_CA/CA; output; end; drop lag_:; run;
Hello,
data want(drop=i j);
set have;
by year;
array state{2} NY CA;
array lagstate{2} lag_NY lag_CA;
do i=1 to dim(state);
lagstate(i)=lag(state(i));
end;
output;
if last.year then do;
type='Percent';
do j=1 to dim(state);
state(j)=lagstate(j)/state(j);
end;
output;
end;
drop lag_:;
run;
/* end of program */
Add more states as required!
Koen
Add this to the program :
title; footnote;
proc sgplot data=work.want;
title "Percent across years";
where type='Percent';
series x=year y=NY / markers;
series x=year y=CA / markers;
format NY CA percent7.2;
yaxis label='Percent attended';
run;
Koen
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.
Find more tutorials on the SAS Users YouTube channel.