Skip to content

Instantly share code, notes, and snippets.

@Atlas7
Last active May 12, 2016 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Atlas7/2c450a890d2f7d5aa369c8a99ed42744 to your computer and use it in GitHub Desktop.
Save Atlas7/2c450a890d2f7d5aa369c8a99ed42744 to your computer and use it in GitHub Desktop.
SAS - count number of colums with array

Say you have a dataset. You wish to find out the number of character columns, numerical columns, and total columns.

One way to do this is to use the SAS array in conjunction with dim() function.

I've created the following code demo to illustrate this - inspired by this SAS blog forum.

data all_chars;
	var1 = "hello";
	var2 = "world";
run;

data all_numerics;
	var1 = 1;
	var2 = 2;
run;

data mixed_types;
	var1 = 1;
	var2 = "hello";
run;

%macro count_columns(inData);
	data outData (keep=numeric_columns char_columns total_columns);
		set &inData. (obs=1);  /* your dataset */
		array nums(*) _numeric_ ;
		array chrs(*) _character_ ;
		if _n_=1 then do;
			numeric_columns = dim(nums);
			char_columns = dim(chrs);
			total_columns = numeric_columns + char_columns;
			output;
		end;
	run;

	data _null_;
		set outData;
		put "inData: &inData.";
		put numeric_columns=;
		put char_columns=;
		put total_columns=;
	run;
%mend;

%count_columns(all_chars);
%count_columns(all_numerics);
%count_columns(mixed_types);

Output:

...

inData: all_chars
numeric_columns=0
char_columns=2
total_columns=2

...

inData: all_numerics
numeric_columns=2
char_columns=0
total_columns=2

...

inData: mixed_types
numeric_columns=1
char_columns=1
total_columns=2

...

There are many ways to do this. This is one of them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment