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

Hi,

I want to create a new dataset (or a column in the existing dataset) that adds the lagged values if a condition is met. Say, the condition is when: 

lagDays<7

then add the corresponding value for the variable "chrg" with its preceding value.  Here is an example for your consideration:  

data have; 
input id $3. chrg lagDays;
datalines;
001 19 .
001 30 23
001 23 45
001 35 1
001 29 2
002 66 .
002 59 34
002 70 19
003 55 .
003 90 10
003 91 4
003 19 6
003 33 1
003 45 22
003 87 1
003 90 1
003 43 45
;
run;

data want; 
input id $3. chrg lagDays adjchrg $20.;
datalines;
001 19 .	19
001 30 23 	30
001 23 45 	23
001 35 1 	23+35
001 29 2 	23+35+29
002 66 . 	66
002 59 34	59
002 70 19	19
003 55 .	55
003 90 10	90
003 91 4	90+91
003 19 6	90+91+19
003 33 1	90+91+19+33
003 45 22	45
003 87 1	45+87
003 90 1	45+87+90
003 43 45	45
;
run;

proc print data=have; run;
proc print data=want; run;

Thanks in advance.

1 ACCEPTED SOLUTION

Accepted Solutions
PaigeMiller
Diamond | Level 26

I'll take a crack, but I'm at home, I have no access to SAS to test this code

 

data want; 
set have;
by id;
if first.id or lagdays>=7 then sum=chrg;
if lagdays<7 then sum+chrg;

datalines;
001 19 .
001 30 23
001 23 45
001 35 1
001 29 2
002 66 .
002 59 34
002 70 19
003 55 .
003 90 10
003 91 4
003 19 6
003 33 1
003 45 22
003 87 1
003 90 1
003 43 45
;
run;
--
Paige Miller

View solution in original post

2 REPLIES 2
PaigeMiller
Diamond | Level 26

I'll take a crack, but I'm at home, I have no access to SAS to test this code

 

data want; 
set have;
by id;
if first.id or lagdays>=7 then sum=chrg;
if lagdays<7 then sum+chrg;

datalines;
001 19 .
001 30 23
001 23 45
001 35 1
001 29 2
002 66 .
002 59 34
002 70 19
003 55 .
003 90 10
003 91 4
003 19 6
003 33 1
003 45 22
003 87 1
003 90 1
003 43 45
;
run;
--
Paige Miller
mamun85
Fluorite | Level 6

Thank you so much! It works like a champ! Really appreciate it!

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!
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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 2 replies
  • 1028 views
  • 0 likes
  • 2 in conversation