DATA Step, Macro, Functions and more

Assigning a variable value in the last record to a new variable.

Reply
N/A
Posts: 0

Assigning a variable value in the last record to a new variable.

I have a SAS table, MYTABLE, with the variable YEAR, among others. The table is sorted by YEAR in ascending order.

The last(highest) YEAR is supposed not to be known in advance.

Since the ascending order by YEAR, I know that the value of YEAR (at least) in the last record contains the last(highest) YEAR.

I want to keep all the records for the last 5 years. If I could assign the value of YEAR in the last record to a variable LASTYEAR I could have the condition

IF YEAR >= LASTYEAR - 4; .

I would prefere to do this in one data step, but two data steps would be OK. I don't want to use PROC SQL.

Is this possible?
Respected Advisor
Posts: 3,777

Re: Assigning a variable value in the last record to a new variable.

[pre]
data allWithLastAge;
set sashelp.class(keep=age rename=age=target) point=nobs nobs=nobs;
put target=;
do until(eof);
set sashelp.class end=eof;
if age eq target then output;
end;
stop;
run;
proc print;
run;
[/pre]
Super Contributor
Posts: 474

Re: Assigning a variable value in the last record to a new variable.

Is it absolutely necessary to have the data sorted in a ascending order?

Normally you just need the data sorted, reversing to descending would simplify greatly the solution by reducing it to a single pass.

Assuming that YEAR is numeric:

data RESULTS;
set DATA;
if _N_ eq 1 then call symput('MAX_YEAR',put(YEAR,best.));
if not (YEAR >= symgetn('MAX_YEAR') -4) then stop;
run;

Cheers from Portugal.

Daniel Santos @ www.cgd.pt
Ask a Question
Discussion stats
  • 2 replies
  • 120 views
  • 0 likes
  • 3 in conversation