Macro Nitems

From sasCommunity
Jump to: navigation, search

Q: How do I get the dimension of a list, i.e.: the number of items?

Quick and Dirty

%Let List = a b c;
%Let Nitems = %eval(%sysfunc(countc(%cmpres(&List.),%str( )))+1);
%Put _global_;


 /*       Name:  2007 Ronald J. Fehd
Requirements  : description  : given a list
                               returns the number of items
                purpose      : provide function
Contexts      : program group: development
                program  type: subroutine
                SAS      type: macro, function
                uses routines: none
Specifications: input  : required: list
                         optional: delimiter
                process: remove leading and multiple blanks
                         check for empty list
                         count occurrences of delimiter
                         return value
                output : value
Usage Examples:
in open code:
%Put Nitems of <%Nitems()>;*err;
%Put Nitems of <%Nitems(List = A B C)>;
%Put Nitems of <%Nitems(List = A B  C   D)>;
%Put Nitems of <%Nitems(List = A+B+C+D,dlm=+)>;
%Put Nitems of <%Nitems(List = A+B!C+D,dlm=!)>;
%Put Nitems of <%Nitems(List = A+B!*C+D,dlm=!*)>;*err;
see test data for macro array
in macro to provide dimension of macro array
macro parameter: list =
%let          DimXyz = %nitems(List = &List.);
%do I = 1 to &DimXyz;
    %local       Xyz&I.;
%array(Name = Xyz
      ,List = &List.);
Information   : author: Ronald J. Fehd
keywords: delimiter, eval, list, macro
*** .................................... */
%MACRO nitems(List    =
             ,dlm     = %str( )
             ,Testing = 0
             ) / des  =
'site: function returns number of items in list'
 /* ** store source /* */
;/* 3/21/2007 RJF2
3/27/2007 RJF2 countC per Toby Dunn
**************************************** */
%let Testing = %eval(    &Testing.
                     or (    %sysfunc(getoption(ECHOAUTO)) NE ECHOAUTO
                         and %sysfunc(getoption(MPRINT)  ) eq MPRINT
                         and %sysfunc(getoption(SOURCE2) ) eq SOURCE2
                         and %sysfunc(getoption(VERBOSE) ) eq VERBOSE));
%if "&Dlm." ne "%str( )"
    and %length(&Dlm.) ge 2 %then %do;
    %let Nitems = ?;
    %put Err%str()or: &SysMacroName.;
    %put dlm<&Dlm.> must be single character;
    %goto ReturnObject;
       %*remove leading and multiple blanks:;
%let   List = %left(%cmpres(&List.));
%local LenList Nitems;
%let   LenList     = %length(&List.);
%if   &Testing.           %then %put _local_;
%if    not  &LenList.     %then %do;
      %let  Nitems = 0;    
      %goto ReturnObject;
%else %if  &LenList. eq 1 %then %do;
      %let  Nitems = 1;   
      %goto ReturnObject;
%let  Nitems = %eval(1 + %sysfunc(countc(&List.,&Dlm.)));
%if   &Testing. %then %put _local_;
%ReturnObject:&Nitems.%mend Nitems;


  • todo

--macro maven == the radical programmer 13:47, 28 January 2009 (EST)