Help using Base SAS procedures

Saving the last/first observation as a variable

Reply
Contributor
Posts: 56

Saving the last/first observation as a variable

Hello everyone,

I hope you are all well.

I am trying to find the quickest way to save the observed value of a variable "pm" at the last "time" for each "id" per "dat" as a variable.

So far I tried this code:

proc sort data=dir.sampler;

by date id time;

run;

data test;

set dir.sampler;

by date id time;

lastpm=last.pm;

run;

But it didn't work with the error "Variable lastpm uninitialized "

so I tried to at least record the last "time";

data test;

set dir.sampler;

by date id time;

lasttime=last.time;

run;

And it didn't work, and the variable lasttime had the value 0 for all the time series.

Any suggestions?

And as always, Thank you!

Regular Contributor
Posts: 168

Re: Saving the last/first observation as a variable

You can use if clause with last. to derive your variable.

Replace this line lastpm=last.pm; with if last.time then variable=value;

Contributor
Posts: 56

Re: Saving the last/first observation as a variable

Hello RamKumar,

If I understand correctly you are suggesting to write the code like so:

data test;

set dir.sampler;

by date id time;

if last.time then lastpm=pm;

run;

In this case, sas just gives lastpm the value of pm.

What do you reckon the problem is?

Thanks

Regular Contributor
Posts: 180

Re: Saving the last/first observation as a variable

Try this:

data test (drop=pm);

set dir.sampler;

by date id time;

lastpm=pm;

if last.time;

run;

Super Contributor
Posts: 333

Re: Saving the last/first observation as a variable

I my be misunderstanding your need, but if you need all the rows to remain and just retain the value of the last pm value then you will have to do something like:

proc sort data=dir.sampler;

     by date id descending time ; /*places last time row first in the dataset*/

run;

data test;

     set dir.sampler;

     by date id descending time;

     if first,id then lastpm = pm;

     retain lastpm; /*keeps the value until changes at the next id*/

run;

I dont have anything to test this with so this is untested code.

Eric

Contributor
Posts: 56

Re: Saving the last/first observation as a variable

Hello Esjackso,

Thanks for you reply. However, it was retaining pm not the last observed pm.

So, based on your code, I created a new dataset with only last observations using this code:

proc sort data=dir.sampler;

     by date id descending time ;

run;

data test;

     set dir.sampler;

     by date id descending time;

     if first.id then output test;

run;

It seems to work. Thanks for your help.


Cheers!

Ask a Question
Discussion stats
  • 5 replies
  • 646 views
  • 0 likes
  • 4 in conversation