Hello there,
I would like to count the number of non 0's and non missing values row-wise.
For example, I have this dataset:
data have;
input name $ A B C D E F G H I J K L;
cards;
AAA 100 50 30 55 66 90 100 110 150 22 0 .
BBB 200 70 30 90 21 80 200 321 456 67 . 0
CCC 300 40 60 40 43 30 300 455 210 57 304 310
;
run;
and I want a column that shows the number of non 0s and non missing per each row:
data want;
input name $ A B C D E F G H I J K L No_Of_Non0_or_Nonmissing;
cards;
AAA 100 50 30 55 66 90 100 110 150 22 0 . 10
BBB 200 70 30 90 21 80 200 321 456 67 . 0 10
CCC 300 40 60 40 43 30 300 455 210 57 304 310 12
;
run;
I have created the following but it is not working as expected:
data attempt;
set have;
array s {*} _numeric_;
by name;
do _i_=1 to dim(s);
if s[_i_] not in (.,0) then do;
if first.name then No_Of_Non0_or_Nonmissing+ 1;
else No_Of_Non0_or_Nonmissing=0;
end;
end;
run;
As you may see it adds the non 0s and non missing values to the next row:
Any help would be much appreciated.
Thanks.
Try this:
data want;
set have;
array x[*] a--l;
do _i=1 to dim(x);
/* The result of the expression is 0 if FALSE, 1 if TRUE */
No_Of_Non0_or_Nonmissing=SUM(No_Of_Non0_or_Nonmissing,x[_i]>0);
end;
/* Get rid of the loop counter */
drop _:;
run;
Try this:
data want;
set have;
array x[*] a--l;
do _i=1 to dim(x);
/* The result of the expression is 0 if FALSE, 1 if TRUE */
No_Of_Non0_or_Nonmissing=SUM(No_Of_Non0_or_Nonmissing,x[_i]>0);
end;
/* Get rid of the loop counter */
drop _:;
run;
You could use something like
ZERO_CNT = count( ' '||catx(' ', of A--L)||' ', ' 0 ');
For non-missing values, use the N() function.
If you just want to count within the observation then why do you have the BY statement and why do you reference FIRST.NAME?
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.