BookmarkSubscribeRSS Feed
Bhargavi221
Fluorite | Level 6

DATA TEST;
INPUT ID$ CTR IS AS2;
CARDS;
AA 0 0 30
AA 2 3 30
AA 28 28 30
BB 10 5 22
BB 0 0 22
BB 12 4 22
;
RUN;

 

OUTPUT:

ID CTR IS A2 A1
AA 0 7 30 30
AA 2 3 30 33
AA 28 28 30 61
BB 0 9 22 22
BB 0 3 22 22
BB 10 5 22 27
BB 12 4 22 31

 

IF FIRST.ID THEN DO;

A1=A2

AND SAME LOOP IF CTR IS 0 THEN A1=A2 ELSE A1+IS(CUMULATIVE SUM)

 

3 REPLIES 3
Ksharp
Super User
DATA TEST;
INPUT ID$ CTR IS AS2;
CARDS;
AA 0 0 30
AA 2 3 30
AA 28 28 30
BB 10 5 22
BB 0 0 22
BB 12 4 22
;
RUN;
data want;
 set test;
 by id;
 if first.id then sum=as2;
  else sum+is;
run;
Bhargavi221
Fluorite | Level 6

Ksharp, Thank you so much for the update.

 

DATA TEST;
INPUT ID$ CTR IS AS2;
CARDS;
AA 0 0 30
AA 2 3 30
AA 28 28 30
BB 10 5 22
BB 0 6 22
BB 12 4 22
;
RUN;

This case your code is summing up to (BB 0 6 22 ) 28, but i need if CTR=0 Then sum= as2 (don't add IS to sum when CTR =0)

Like below:

ID CTR IS AS2 sum
AA 0 0 30 30
AA 2 3 30 33
AA 28 28 30 61
BB 10 5 22 22
BB 0 6 22 22
BB 12 4 22 26

 

 

novinosrin
Tourmaline | Level 20

just a very small tweak to Ksharp's code:

 

DATA TEST;
INPUT ID$ CTR IS AS2;
CARDS;
AA 0 0 30
AA 2 3 30
AA 28 28 30
BB 10 5 22
BB 0 0 22
BB 12 4 22
;
RUN;


data want;
 set test;
 by id;
 if first.id or ctr=0 then  sum=as2;
  else   sum+is;
run;

 

 

 

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

Register now

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
  • 1436 views
  • 0 likes
  • 3 in conversation