BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
desireatem
Pyrite | Level 9

Hello Sir/Madam,

 

I have this longitudinal data that I wish to sum by each id, for example the data is;

Data DD;

Input id A;

Cards;

1     2

1    5

1    3

1     1 

2    2

2     1

2       3;

 

I want to create a new data by summing A by id such that the new data will be;

id   sum_A

1   11(2+5+3+1)

2   6

 

Please help.

 

Best,

DA

1 ACCEPTED SOLUTION

Accepted Solutions
PeterClemmensen
Tourmaline | Level 20
data dd;
Input id A;
cards;
1 2
1 5
1 3
1 1
2 2
2 1
2 3
;

proc summary data=dd nway;
   class id;
   var A;
   output out=want(drop=_:) sum(A)=sum_A;
run;

View solution in original post

5 REPLIES 5
Shmuel
Garnet | Level 18
proc summary data=have;
   class ID;
   var a;
   output out=want sum=;
run;
PeterClemmensen
Tourmaline | Level 20
data dd;
Input id A;
cards;
1 2
1 5
1 3
1 1
2 2
2 1
2 3
;

proc summary data=dd nway;
   class id;
   var A;
   output out=want(drop=_:) sum(A)=sum_A;
run;
desireatem
Pyrite | Level 9

Thank you!

s_lassen
Meteorite | Level 14

Always more than one way to do things in SAS. Apart from PROC SUMMARY, you can use a data step:

data want;
  do until(last.id);
    set dd;
    by id;
    sum_A=sum(sum_A,A);
    end;
  drop A;
run;

 

Or SQL:

proc sql;
  create table want as select
    id,
    sum(A) as sum_A
    from dd
    group by id
    ;
quit;

The first solution requires the data to be sorted, but may be faster if it already is sorted. But not necessarily; if SAS knows that the data is sorted (you used a PROC SORT or an SQL ORDER BY statement to create it), the two are probably equivalent. The same goes for PROC SUMMARY, where you can use BY ID instead of CLASS ID if the data is already sorted, which again may perform better if does not know that the data is sorted.

 

Normally, PROC SQL will deliver the data in the GROUP BY order, but this is not guaranteed behavior, so you may want to add an ORDER BY ID at the end of the SQL query, then it's explicit. 

desireatem
Pyrite | Level 9

Thank you very much!

FA

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
  • 5 replies
  • 1793 views
  • 1 like
  • 4 in conversation