## count all values in the field and create new var

Solved
Frequent Contributor
Posts: 81

# count all values in the field and create new var

Hi,

Have

data;

var1 var2 var3 var4

-1     20    4      -1

60   -1     -1      -1;

run;

want;

var1 var2 var3 var4   want              (counts number of vars with -1)

-1     20    4      -1         2

60   -1     -1      -1;        3

I have some vars with -1 value, I want to count how many vars have -1 values. Any ideas?

Thank you

Accepted Solutions
Solution
‎02-08-2017 01:51 PM
Super User
Posts: 7,932

## Re: count all values in the field and create new var

[ Edited ]

Use an array and loop over the array count how many members equal minus one.

``````data want;
set have;
array x var1-var4 ;
want=0;
do i=1 to dim(x);
want + (x(i)=-1);
end;
run;
``````

But if you changed your coding and replaced -1 with missing value (or one of the 27 special missing values) then you could use NMISS() function.  Plus you could use other functions like MIN(),MAX(), MEAN() on the set of variables since they would ignore the missing values.

``````data have;
input var1-var4 ;
cards;
. 20  4  .
60  .  .  .
;

data want;
set have ;
want = nmiss(of var1-var4);
run;``````

All Replies
Super User
Posts: 9,869

## Re: count all values in the field and create new var

Use array processing

``````data want;
set have;
array vars {*} _numeric_;
count = 0;
do i = 1 to dim(vars);
if vars{i} = -1 then count + 1;
end;
drop i;
run;``````
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
Solution
‎02-08-2017 01:51 PM
Super User
Posts: 7,932

## Re: count all values in the field and create new var

[ Edited ]

Use an array and loop over the array count how many members equal minus one.

``````data want;
set have;
array x var1-var4 ;
want=0;
do i=1 to dim(x);
want + (x(i)=-1);
end;
run;
``````

But if you changed your coding and replaced -1 with missing value (or one of the 27 special missing values) then you could use NMISS() function.  Plus you could use other functions like MIN(),MAX(), MEAN() on the set of variables since they would ignore the missing values.

``````data have;
input var1-var4 ;
cards;
. 20  4  .
60  .  .  .
;

data want;
set have ;
want = nmiss(of var1-var4);
run;``````

☑ This topic is solved.

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

Discussion stats
• 2 replies
• 256 views
• 1 like
• 3 in conversation