LISTSERV at the University of Georgia
Menubar Imagemap
Home Browse Manage Request Manuals Register
Previous messageNext messagePrevious in topicNext in topicPrevious by same authorNext by same authorPrevious page (January 2004, week 4)Back to main SAS-L pageJoin or leave SAS-L (or change settings)ReplyPost a new messageSearchProportional fontNon-proportional font
Date:   Sat, 24 Jan 2004 18:27:58 -0500
Reply-To:   "Richard A. DeVenezia" <radevenz@IX.NETCOM.COM>
Sender:   "SAS(r) Discussion" <SAS-L@LISTSERV.UGA.EDU>
From:   "Richard A. DeVenezia" <radevenz@IX.NETCOM.COM>
Subject:   Re: a question on counting

"Yuan C." <peppermint_jojo@YAHOO.COM> wrote in message news:200401241908.i0OJ82S11056@listserv.cc.uga.edu... > Dear SAS-L: > I want to count the number of appearance of 3 in each observation, and > generate a new variable: count. But I got unexpected results using the > following code... Can someone help on this? thanks!! > -------------------------- > DATA: > ------------------------ > Obs SEQ REL_1 REL_2 REL_3 REL_4 REL_5 REL_6 REL_7 REL_8 > > 1 42 01 3 3 3 3 3 > 2 47 01 3 3 > 3 51 01 3 4 > 4 91 01 3 3 > 5 92 01 3 3 3 3 > 6 115 01 3 > 7 132 01 3 > 8 140 01 3 > .... ... ... > --------------------------- > My code: > ------------------------ > > DATA CHILD1; SET LTC99_1 (KEEP=SEQ REL_1-REL_20); > count=0; > do i=1 to 20; > retain count; > %macro count(var); > %if rel_&var='3' %then count=count+1; %else count=count; > %mend count; > end; > output; > RUN; QUIT;

Yuan:

You are showing classic symptons; improper mixing of Macro and DATA Step environments. My recommendation is to forget macro for now and concentrate on getting a good understanding of DATA Step arrays.

array rel rel_1-rel_20; count=0; do i = 1 to 20; count + (rel[i] = 3); end;

(rel=3) is a boolean expression that evaluates as follows: true is 1 false is 0

count + expression is a shortcut for count=count+expression with the side effect that count is auto retained (retaining in this step is not needed, I just like the shorter form. As long as count is reset to 0 prior to using it everything works fine)

Looking forward to your next question... you can do a mini-histogram (or freq study) of each row; if you know the range of values to be encountered in variables rel_1 - rel_20. Suppose min is -10 and max is 20.

You can then have

array counts[-10:20] _temporary_; do i = -10 to 20; counts[i]=0; end; do i = 1 to 20; counts[rel[i]] + 1; end;

DATA Step arrays will server you well and long. When they don't or can't, then it may be time to investigate using Macro to solve you problems.

-- Richard A. DeVenezia http://www.devenezia.com/downloads/sas/macros/


Back to: Top of message | Previous page | Main SAS-L page