DATA Step, Macro, Functions and more

Last.X and First.X on the same time

Accepted Solution Solved
Reply
Regular Contributor
Posts: 210
Accepted Solution

Last.X and First.X on the same time

Hi all,

 

For instance a dataset is sorted by variable X.

 

How in one iteration reveal if an observation is only one in a group:

 

if first.X and last.X ...

 

Thank you! 


Accepted Solutions
Solution
‎02-16-2018 10:20 AM
Super User
Super User
Posts: 9,415

Re: Last.X and First.X on the same time

Posted in reply to DmytroYermak

Thats it you have it.  

data want;
  set have;
  by x;
  if first.x and last.x then only_one="Yes";
  else only_one="No";
run;

View solution in original post


All Replies
Solution
‎02-16-2018 10:20 AM
Super User
Super User
Posts: 9,415

Re: Last.X and First.X on the same time

Posted in reply to DmytroYermak

Thats it you have it.  

data want;
  set have;
  by x;
  if first.x and last.x then only_one="Yes";
  else only_one="No";
run;
Regular Contributor
Posts: 210

Re: Last.X and First.X on the same time

You are definitely right ). It was rather a "tough" day today (
Super User
Super User
Posts: 9,415

Re: Last.X and First.X on the same time

Posted in reply to DmytroYermak

No probs, it likely not be the first or last tough day!

Contributor
Posts: 37

Re: Last.X and First.X on the same time

[ Edited ]
Posted in reply to DmytroYermak

Hi,

 

If you sort a data set  and in a data step when you specify by variable then sas creates two automatic variables back end they are first.by variable and last.by variable.

 

first.by variable value is=1 for the first observation in a dataset and rest of all the by group will be =0 except last.by variable. that will be one

 

You can observe it by writing example

 

proc sort data=ds;
by sex;
run;
data ds;
set sashelp.classfit;
by sex;
put _all_;'

if first.sex and last.x then flag=1;

else flag=0;
run;

 

Thanks

☑ This topic is solved.

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

Discussion stats
  • 4 replies
  • 145 views
  • 0 likes
  • 3 in conversation