DATA Step, Macro, Functions and more

grouping in macro

Accepted Solution Solved
Reply
Occasional Contributor
Posts: 17
Accepted Solution

grouping in macro

Hi,

I have a following data step which breaks entire observation by 10%  (eg. entire observation is 1896, and break the data set by 10% (1806 *10% = 189.6 ~= 190 )  )

Is there any way to group using macro so I don't need to change the parameters manually when the number of observation changes ? Thank you

DATA want

  SET have;

  if _n_<= 190 then grp=1;

else if 190 <_n_<=380 then grp=2;

else if 380 <_n_<=570 then grp=3;

else if 570 <_n_<=760 then grp=4;

else if 760 <_n_<=950 then grp=5;

else if 950 <_n_<=1140 then grp =6;

else if 1140 <_n_<=1330 then grp=7;

else if 1330 <_n_<=1520 then grp=8;

else if 1520 <_n_<=1710 then grp=9;

  grp=10;

RUN;


Accepted Solutions
Solution
‎07-08-2014 09:57 AM
Super User
Posts: 10,044

Re: grouping in macro

Posted in reply to davidnamh

Why not use proc rank ?

data class;
 set sashelp.class;
 n+1;
 run;
 proc rank data=class out=want groups=5;
 var n;
 ranks group;
 run;

Xia Keshan

View solution in original post


All Replies
Contributor
Posts: 29

Re: grouping in macro

Posted in reply to davidnamh

Hi davidnamh,

Hope this code will be helpful.

data bug;

set have;

count+1;

run;

proc sql;

create table want as select *, ceil(count/max(count)*0.10)) as grp from bug;

quit;

Super Contributor
Posts: 340

Re: grouping in macro

Posted in reply to davidnamh

Hi!

I Think Proc Rank would be really an option:

Proc Rank Data=In_File Out=Result Groups=10;

  Var <Variable>;

  Ranks <Group_Name>;

Run;

Valued Guide
Posts: 2,177

Re: grouping in macro

Posted in reply to davidnamh

No macro No macro required!

The SET statement has an option NOBS= which names a variable into which the data step compiler will place that number of "obs in the dataset".

You'll need to rewrite your code just a little (it could be a lot shorter)

data want ;

set have nobs= nobs ;

*grp = int( _n_/nobs) +1;

  grp = int((_n_-1)/nobs)+1 ;

run ;

Solution
‎07-08-2014 09:57 AM
Super User
Posts: 10,044

Re: grouping in macro

Posted in reply to davidnamh

Why not use proc rank ?

data class;
 set sashelp.class;
 n+1;
 run;
 proc rank data=class out=want groups=5;
 var n;
 ranks group;
 run;

Xia Keshan

🔒 This topic is solved and locked.

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

Discussion stats
  • 4 replies
  • 226 views
  • 0 likes
  • 5 in conversation