BookmarkSubscribeRSS Feed
benjaminchua002
Calcite | Level 5

I have two arrays, year and yearsum. Yearsum is the sum of values for each year. 

 

I am trying to create a new row 'Total' and use the yearsum values as the total values. My code works but it's incredibly inefficient. I am not sure if I can use a DO loop because it will generate 10 rows of 'Total'. 

 

if last then do;
Variable = 'Total';
year1 = yearsum1;
year2 = yearsum2;
year3 = yearsum3;
year4 = yearsum4;
year5 = yearsum5;
year6 = yearsum6;
year7 = yearsum7;
year8 = yearsum8;
year9 = yearsum9;
year10 = yearsum10;
output;
end;

Is there a way to write year{i} = yearsum {i} more efficiently?

I did a DO loop for the top portion but I can't apply it to the above code.

do i = 1 to 10;
yearsum{i} = sum(yearsum{i}, year{i});
end;

End result:

Capture.PNG

4 REPLIES 4
Shmuel
Garnet | Level 18

You just need to define ARRAY statements:

array year year1-year10;
array yearsum yearsum1-yearsum10;

do i = 1 to 10;
    yearsum{i} = sum(yearsum{i}, year{i});
end;
PaigeMiller
Diamond | Level 26

Yes, you could use arrays, but any time you have a wide data set, with a specific year in the variable names (or any calendar information in the variable names), you have chosen a data arrangement that is more difficult to work with, and probably requires a lot more programming than if you kept the data in a long format, with year as a variable containing values 1 through 10.

 

You see, SAS already provides several built-in methods of doing what you are trying to do, they have done the work so you don't have to, if you use a long data set, then you have much less programming. PROC REPORT get this output table easily, without you having to do all the coding of individual years.


See Maxim 19. Embrace long data sets. Make your coding simpler.

--
Paige Miller
Kurt_Bremser
Super User

A simplified example for using the longitudinal dataset in PROC REPORT:

data have;
input variable $ year value;
datalines;
A 1 111
A 2 222
A 3 333
B 1 444
B 2 555
B 3 666
;

proc report data=have;
column variable year,value;
define variable / group;
define year / across;
define value / "" sum;
run;

Ready to join fellow brilliant minds for the SAS Hackathon?

Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.

Register today!
Mastering the WHERE Clause in PROC SQL

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.

Discussion stats
  • 4 replies
  • 423 views
  • 0 likes
  • 4 in conversation