BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
Quartz | Level 8

Count number of Non Zeros and Non Missing by row in a dataset

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.

1 ACCEPTED SOLUTION

Accepted Solutions
SAS Super FREQ

Re: Count number of Non Zeros and Non Missing by row in a dataset

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;
Check out my Jedi SAS Tricks for SAS Users
3 REPLIES 3
SAS Super FREQ

Re: Count number of Non Zeros and Non Missing by row in a dataset

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;
Check out my Jedi SAS Tricks for SAS Users
Tourmaline | Level 20

Re: Count number of Non Zeros and Non Missing by row in a dataset

You could use something like

ZERO_CNT = count( ' '||catx(' ', of A--L)||' ', ' 0 ');

For non-missing values, use the N() function.

Super User

Re: Count number of Non Zeros and Non Missing by row in a dataset

If you just want to count within the observation then why do you have the BY statement and why do you reference FIRST.NAME?

Discussion stats
• 3 replies
• 415 views
• 1 like
• 4 in conversation