BookmarkSubscribeRSS Feed
deleted_user
Not applicable
Is there a simple way to determine the number of distinct values in an observation?

I'm working with many columns with integer values. I can use descriptive statistics to determine the number of (non-missing) values or the minimum value etc.

numentries = n(of col_start--col_end)
minvalue = min(of col_start--col_end)

Many values are repeated. I would like to know the number of distinct values there are for each observation.
3 REPLIES 3
deleted_user
Not applicable
Hi JohnI,

I'm not sure what you mean by simple, but something like this might help:

data have;
input id var1 var2 var3 var4 var5;
cards;
1 1 2 3 4 5
2 1 2 2 3 4
3 3 3 2 1 3
4 4 1 2 3 1
;
run;

data want(keep=id var1--var5 n distinct);
set have;
array v_(*) var1--var5;
array _dist_(10) _temporary_;
do j = 1 to 10;
_dist_(j) = .;
end;
do i = 1 to dim(v_);
_dist_(v_(i)) = 1;
end;
distinct = 0;
do j = 1 to 10;
if _dist_(j) ne . then distinct = distinct + 1;
end;
n = n(of var1--var5);
run;

I've only used five variables and a limit of 10 for the value, but you could extend this for n variables and a wide range of integer values.

Robert
deleted_user
Not applicable
Thank you Robert.

By simple I meant a 'one-liner' like N or Max.

But, I was able to use your code for my needs (and I learned something too).

Thanks again, John
Cynthia_sas
Diamond | Level 26
Hi:
You could also investigate the NLEVELS option of PROC FREQ or just proc freq in general:
[pre]
data have;
input id var1 var2 var3 var4 var5;
cards;
1 1 2 3 4 5
2 1 2 2 3 4
3 3 3 2 1 3
4 4 1 2 3 1
;
run;

proc freq data=have nlevels;
table _numeric_;
run;
[/pre]

cynthia

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

What is Bayesian Analysis?

Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 1764 views
  • 0 likes
  • 2 in conversation