DATA Step, Macro, Functions and more

Use previous row value of one variable for a new variable

Accepted Solution Solved
Reply
Contributor
Posts: 24
Accepted Solution

Use previous row value of one variable for a new variable

[ Edited ]

I have a table where I need a new variable (P_Current) that takes value of the previous value of variable (Current) . The following highlights what I am looking for:

 

IDCurrentP_Current
111
201
210
301
400
510
611

 

I was trying the following but thats probably not correct

 

data test2;
set test1;
by ID;
P_Current = lag(Current);
if first.ID then P_Current = Current;
run;

 


Accepted Solutions
Solution
‎08-24-2017 11:34 PM
PROC Star
Posts: 1,760

Re: Use previous row value of one variable for a new variable

Your output seems to macth this code:

data test2;
set test1;
P_Current = lag(Current);
if _N_=1 then P_Current = Current;
run;

View solution in original post


All Replies
Solution
‎08-24-2017 11:34 PM
PROC Star
Posts: 1,760

Re: Use previous row value of one variable for a new variable

Your output seems to macth this code:

data test2;
set test1;
P_Current = lag(Current);
if _N_=1 then P_Current = Current;
run;
Contributor
Posts: 24

Re: Use previous row value of one variable for a new variable

Thanks Chris. However, that code does not seem to be working. I have slightly edited the original post table. Ideally I am looking to populate the P_Current field with the last Current value (i.e. value from the previous row). With the code you suggested, the P_Current is populated with all 1s. Any idea where I might be going wrong?
Respected Advisor
Posts: 4,932

Re: Use previous row value of one variable for a new variable

@ChrisNZ's code is working:

 

data test1;
input ID Current;
datalines;
1 1
2 0
2 1
3 0
4 0
5 1
6 1
;

data test2;
set test1;
P_Current = lag(Current);
if _N_=1 then P_Current = Current;
run;

proc print data=test2 noobs; run; 
                            ID    Current    P_Current

                              1       1           1
                              2       0           1
                              2       1           0
                              3       0           1
                              4       0           0
                              5       1           0
                              6       1           1

Please post the code you tried.

 

PG
Contributor
Posts: 24

Re: Use previous row value of one variable for a new variable

my apologies! i got the code wrong. chris's code is indeed correct.
☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 4 replies
  • 195 views
  • 1 like
  • 3 in conversation