数据集列名称转换为宏变量

时间:2018-07-23 09:38:30

标签: sas

欢迎大家(这是我的第一篇文章)

[问题]将所有列名称放入宏变量的最简单方法是什么? 高级版本,将数字(列中的值)列名称放入一个宏变量,将所有字符列名称放入另一宏变量?

致谢 香港

3 个答案:

答案 0 :(得分:1)

在dictionary.columns中使用proc sql into子句是为您的目的制作宏变量的最简单方法之一。下面的查询使用sashelp.class,您可以改用表名和li​​bname

/* for all variables*/
Proc sql noprint;
select name into :macvar1 separated by ',' from
dictionary.columns
where upcase(memname) = 'CLASS'
and upcase(libname)  = 'SASHELP';

/* for numeric variables*/
 Proc sql noprint;
 select name into :macvar2 separated by ',' from
 dictionary.columns
 where upcase(memname) = 'CLASS'
 and upcase(libname)  = 'SASHELP'
 and upcase(type) = 'NUM';


  /* for character variables*/
  Proc sql noprint;
 select name into :macvar3 separated by ',' from
 dictionary.columns
 where upcase(memname) = 'CLASS'
and upcase(libname)  = 'SASHELP'
and upcase(type) = 'CHAR';

%put value of all variables is &macvar1;
%put value of numeric variables is &macvar2;
%put value of character variables is &macvar3;

答案 1 :(得分:1)

如果您需要对多个表执行此操作,则可以尝试为此定义一个宏,例如:

%macro get_cols(lib,mem,mvar,type);
   %global &mvar;

   proc sql noprint;
      select
         name
      into
         :&mvar separated by ' '
      from
         dictionary.columns
      where
             libname eq upcase("&lib")
         and memname eq upcase("&mem")

         %if %upcase(&type) ne ALL %then
         and upcase(type) eq upcase("&type");

      ;
   quit;

   %put &mvar = &&&mvar;
%mend get_cols;

然后您可以根据需要调用它:

/* character variables */
%get_cols(sashelp,class,cvars,char);

/* numeric variables */
%get_cols(sashelp,class,nvars,num);

/* all variables */
%get_cols(sashelp,class,vars,all);

答案 2 :(得分:1)

根据您的操作,您还可以使用_character_引用所有字符变量,并使用_numeric_引用数字变量。

*doesn't do anything but illustrates how to reference all variables of a specific type;
data want;
   set sashelp.class;
   array _c1(*) _character_;
   array _n1(*) _numeric_;

run;