I need to count how many numbers starting with '1' '2' '3's in each observation.
There are 700 variables and 50000 observations.
I use the following code,
data want;
set have;
array chars $ chars1-char700;
array counts counts1-counts3;
do over chars ;
if substr(chars,1,1)=1 then counts1+1;
if substr(chars,1,1)=2 then counts2+1;
if substr(chars,1,1)=3 then counts3+1;
end;
run;
but the counts on each observation is adding on top of the result (counts) from the last observation.
How can I count them for each observation? (the counts need to star from 0 for each observation)
Many thanks
data want;
set have;
array chars $ chars1-char700;
array counts counts1-counts3;
counts1=0;counts2=0;counts3=0;
do over chars ;
if substr(chars,1,1)=1 then counts1+1;
if substr(chars,1,1)=2 then counts2+1;
if substr(chars,1,1)=3 then counts3+1;
end;
run;
Do you only have 1,2,3?
To answer your initial question counts1+1 creates an implicit retain, change the counter to counts1=counts1+1 or explicitly set the variables to 0 at the beginning of each loop
Thanks Reeza,
I tried count1=count1+1, it doesn't count the number at all. I don't know why. Do I need to set count1=0 at the beginning?
BTW, how can I set counts back to 0 at the beginning of the loop?
Cheers
On top of Reeza's suggestions, you can also set counts missing for every data step iteration:
call missing (of counts(*)); Some simplification has also been suggested in the following code:
data want;
set have;
array chars chars1-chars700;
array counts counts1-counts3;
call missing(of counts(*));
do over chars;
counts(input(first(chars),1.))+1;
end;
run;
Thanks Hai,
I'm not sure I understand it.
Is the count missing can reset variables to 0 ?
Cheers,
data want;
set have;
array chars $ chars1-char700;
array counts counts1-counts3;
counts1=0;counts2=0;counts3=0;
do over chars ;
if substr(chars,1,1)=1 then counts1+1;
if substr(chars,1,1)=2 then counts2+1;
if substr(chars,1,1)=3 then counts3+1;
end;
run;
Hi Reeza;
It still sum up the counts..
Hi Reeza,
I miss typed the name.
It works!! Thanks a lot!
Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.
Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.