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


data have;
input number;
cards;
12
10
8
6
4
2
run;

 

 

data want;
set have;
lag_d = lag(number) - number;
run;

 

when i run this code i am getting like this 

 

 

Obs number lag_d
1 12 .
2 10 2
3 8 2
4 6 2
5 4 2
6 2 2

 

but i need the ouput like this insted of staring . i need the valus from frist row

 

Obs number lag_d
1 12 2
2 10 2
3 8 2
4 6 2
5 4 2
6 2 0
1 ACCEPTED SOLUTION

Accepted Solutions
Ksharp
Super User

data have;
input number;
cards;
12
10
8
6
4
2
;
run;

data want;
 merge have have(keep=number rename=(number=_n) firstobs=2);
 lag_d=number-_n;
 if missing(lag_d) then lag_d=0;
 drop _n;
run;

View solution in original post

2 REPLIES 2
PeterClemmensen
Tourmaline | Level 20

What you want to do is to simulate a lead function. It can be done like this

 

data have;
input number;
cards;
12
10
8
6
4
2
run;
 
data have;
   set have;

   if eof=0 then
      set have (firstobs=2 keep=number rename=(number=lead_number)) end=eof;
   else lead_number=.;

   lag_d = number - lead_number;
run; 

Bear in mind though, that the last value of your lag_d variable will be missing with this solution, which I think is more approprate than it being zero, since you do not know the next value of number. This can be corrected fairly easily though 🙂

Ksharp
Super User

data have;
input number;
cards;
12
10
8
6
4
2
;
run;

data want;
 merge have have(keep=number rename=(number=_n) firstobs=2);
 lag_d=number-_n;
 if missing(lag_d) then lag_d=0;
 drop _n;
run;

sas-innovate-2024.png

Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.

Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

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.

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
  • 769 views
  • 2 likes
  • 3 in conversation