BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
everyone
Fluorite | Level 6

I'm wondering what's the best way to create a variable that contains a column's total sum inside of a data step. Can this be easily achieved without proc sql?

 

As an example, I'd like to create a new variable, total_age, that contains the sum of all the students' ages, in the sashelp.class dataset. My code below creates a cumulative sum, but how would I revise to create a total so that each row displays the total age? Thank you.  

 

data sas_intro;
set sashelp.class;
retain;
total_age = sum(total_age, age); /*creates cumulative sum, not total)*/
run;
1 ACCEPTED SOLUTION

Accepted Solutions
PeterClemmensen
Tourmaline | Level 20

A data step approach

 

data want;
   if _N_ = 1 then do;
      do until (z);
         set sashelp.class end = z;
         total_age = sum(total_age, age);
         retain total_age;
      end;
   end;

   set sashelp.class;
   
run;

View solution in original post

3 REPLIES 3
Reeza
Super User

It's either two steps in a data step (calculation + merge) or a DoW loop. Programmatically, SQL is much easier here for sure.

Depending on what you're doing, for example creating a report, the reporting procedure may be better suited to doing that as well.

 

data sas_intro;
do _n_ =1 by 1 until(eof);
set sashelp.class end=eof;
total_age = sum(total_age, age); /*creates cumulative sum, not total)*/
end;

do _n_ =1 by 1 until(eof2);
set sashelp.class end=eof2;
output;
end;


run;

Other methods illustrated here:

https://github.com/statgeek/SAS-Tutorials/blob/master/add_average_value_to_dataset.sas

 

 

PeterClemmensen
Tourmaline | Level 20

An SQL approach

 

proc sql;
   create table want as
   select *
        , sum(age) as total_age 
   from sashelp.class
   ;
quit;
PeterClemmensen
Tourmaline | Level 20

A data step approach

 

data want;
   if _N_ = 1 then do;
      do until (z);
         set sashelp.class end = z;
         total_age = sum(total_age, age);
         retain total_age;
      end;
   end;

   set sashelp.class;
   
run;

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 1476 views
  • 5 likes
  • 3 in conversation