【问题标题】:Parse all column names from table and put into macro variable (SAS 9.4)从表中解析所有列名并放入宏变量(SAS 9.4)
【发布时间】:2018-02-02 10:42:24
【问题描述】:

您好,我有一个包含大约 300 个变量的表,我需要将所有列名(变量)放入一个宏变量(%let vars = [list of names of those 300 columns])中。

有人知道我该怎么做吗?

【问题讨论】:

    标签: sas sas-macro


    【解决方案1】:

    SAS字典保存元数据,用字典很容易得到数据的列名,如:

    proc sql;
       select name into: vars separated by ' ' from dictionary.columns where libname='SASHELP' and memname='CLASS';
    quit;
    
    %put &vars;
    

    或数据步中的Vcolumn:

    data _null_;
       set sashelp.vcolumn(where=(libname='SASHELP' and memname='CLASS')) end=last;
       length vars $100;
       retain vars;
       vars=catx(' ', vars,name);
       if last then call symputx('vars',vars);
       run;
    %put &vars;
    

    【讨论】:

      【解决方案2】:

      在 MacroCore library 中有一个用于此的宏,其工作原理如下:

      %put List of Variables=%mf_getvarlist(sashelp.class);
      

      转载如下:

      /**
        @file
        @brief Returns dataset variable list direct from header
        @details WAY faster than dictionary tables or sas views, and can
          also be called in macro logic (is pure macro). Can be used in open code,
          eg as follows:
      
              %put List of Variables=%mf_getvarlist(sashelp.class);
      
        returns:
        > List of Variables=Name Sex Age Height Weight
      
        @param libds Two part dataset (or view) reference.
        @param dlm= provide a delimiter (eg comma or space) to separate the vars
      
        @version 9.2
        @author Allan Bowe
        @copyright GNU GENERAL PUBLIC LICENSE v3
      **/
      
      %macro mf_getvarlist(libds
            ,dlm=%str( )
      )/*/STORE SOURCE*/;
        /* declare local vars */
        %local outvar dsid nvars x rc dlm;
        /* open dataset in macro */
        %let dsid=%sysfunc(open(&libds));
      
        %if &dsid %then %do;
          %let nvars=%sysfunc(attrn(&dsid,NVARS));
          %if &nvars>0 %then %do;
            /* add first dataset variable to global macro variable */
            %let outvar=%sysfunc(varname(&dsid,1));
            /* add remaining variables with supplied delimeter */
            %do x=2 %to &nvars;
              %let outvar=&outvar.&dlm%sysfunc(varname(&dsid,&x));
            %end;
          %End;
          %let rc=%sysfunc(close(&dsid));
        %end;
        %else %do;
          %put unable to open &libds (rc=&dsid);
          %let rc=%sysfunc(close(&dsid));
        %end;
        &outvar
      %mend;
      

      【讨论】:

      • 这工作谢谢!顺便说一句,您知道如何获取变量列表的长度吗?比如,里面放了多少个名字。
      • %put word count = %sysfunc(countw(&vars));
      猜你喜欢
      • 1970-01-01
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      相关资源
      最近更新 更多