Help using Base SAS procedures

elegant way to format percent outputs

Accepted Solution Solved
Reply
Super Contributor
Posts: 301
Accepted Solution

elegant way to format percent outputs

Hi guys, anyone can help me to simplify my code in the way to format my final dataset want?...maybe using loops rather than write down by hand the 4 combinations (class/type)?

data new;

input name  class $ type $;

datalines;

1 a yes

2 a no

3 a yes

4 b no

5 b yes

6 a  yes

7 b no

8 b no

9 b yes

10 a yes

11 a yes

;

run;

*creating macrovariables;


proc sql noprint;

select count(distinct name) into: safea

from new

where class='a';

quit;

proc sql noprint;

select count(distinct name) into: safeb

from new

where class='b';

quit;

%put &safea;

%put &safeb;

proc sql noprint;

create table test as

select distinct class, type, count(distinct name) as n

from new

group by class,type;

quit;

*creating the format of my want dataset;

data want;

set test;

if class='a' and type='yes' then nc=put(n,best12.)||'('||put(n/&safea*100,5.1)||')';

if class='a' and type='no' then nc=put(n,best12.)||'('||put(n/&safea*100,5.1)||')';

if class='b' and type='yes' then nc=put(n,best12.)||'('||put(n/&safeb*100,5.1)||')';

if class='b' and type='no' then nc=put(n,best12.)||'('||put(n/&safeb*100,5.1)||')';

drop n;

run;

Thanks

V.


Accepted Solutions
Solution
‎03-10-2013 09:51 PM
Respected Advisor
Posts: 4,920

Re: elegant way to format percent outputs

You could do this more compactly as folows :

proc sql;

create table want as

select

     class,

     type,

     catt(ncCount, " (", put(100*ncCount/sum(ncCount), 5.1), ")") as nc

from (select class, type, count(*) as ncCount from new group by class, type)

group by class;

quit;

PG

PG

View solution in original post


All Replies
Solution
‎03-10-2013 09:51 PM
Respected Advisor
Posts: 4,920

Re: elegant way to format percent outputs

You could do this more compactly as folows :

proc sql;

create table want as

select

     class,

     type,

     catt(ncCount, " (", put(100*ncCount/sum(ncCount), 5.1), ")") as nc

from (select class, type, count(*) as ncCount from new group by class, type)

group by class;

quit;

PG

PG
Super User
Posts: 19,772

Re: elegant way to format percent outputs

I prefer using procedures, such as proc freq.

proc sort data=new; by class type;

proc freq data=new noprint;

by class;

table type/out=want1 totpct;

run;

data want2;

  set want1;

  nc=cat("", trim(strip(put(count, 8.))), "(",trim(strip(put(percent/100, percent8.1))), ")");

run;


Super Contributor
Posts: 301

Re: elegant way to format percent outputs

Just Brilliant, Thank you.

🔒 This topic is solved and locked.

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

Discussion stats
  • 3 replies
  • 197 views
  • 3 likes
  • 3 in conversation