SAS:如何测试变量是否为数字

时间:2014-02-21 14:43:31

标签: sas

我正在寻找一个简单的函数来告诉我给定数据集的给定变量是否为数字。

我想在宏语言的if语句中使用它:

%if isNumeric(ds,var) %then %do ...

但我找不到任何方法来实现这一点。你知道这是否可行?

我知道这可能是微不足道的,但任何帮助都会受到赞赏!

谢谢!

3 个答案:

答案 0 :(得分:4)

假设您想知道实际的类型,而不是变量的内容,有一个vartype(dsid,var-num) function,它具有您需要的确切规格,除了var-num不需要var-name。文档中的这个例子可以帮助您入门;你可以调整它来使用它来计算出一个特定的变量。

%let dsid=%sysfunc(open(mydata,i));
%let varlist=;
%do i=1 %to %sysfunc(attrn(&dsid,nvars));
  %if (%sysfunc(vartype(&dsid,&i)) = N) %then
     %let varlist=&varlist %sysfunc(varname
                                 (&dsid,&i));
%end;
%let rc=%sysfunc(close(&dsid));

答案 1 :(得分:1)

您最近编辑了自己的问题,因此我认为我会为以下"简单的功能做出贡献":

%if %mf_getvartype(sashelp.class,age)=N %then %put This var is numeric;
%if %mf_getvartype(sashelp.class,name)=C %then %put This var is character;

宏人核心库here中提供了mf_getvartype宏功能,并在下面转载:

/**
  @file
  @brief Returns variable type - Character (C) or Numeric (N)
  @details
Usage:
      data test;
         length str $1.  num 8.;
         stop;
      run;
      %put %mf_getvartype(test,str);
      %put %mf_getvartype(work.test,num);
  @param libds Two part dataset (or view) reference.
  @param var the variable name to be checked
  @return output returns C or N depending on variable type.  If variable
    does not exist then a blank is returned and a note is written to the log.
  @version 9.2
  @author Allan Bowe
  @copyright GNU GENERAL PUBLIC LICENSE v3
**/

%macro mf_getvartype(libds /* two level name */
      , var /* variable name from which to return the type */
    );
  %local dsid vnum vtype rc;
  /* Open dataset */
  %let dsid = %sysfunc(open(&libds));
  %if &dsid. > 0 %then %do;
    /* Get variable number */
    %let vnum = %sysfunc(varnum(&dsid, &var));
    %if(&vnum. > 0) %then
       /* Get variable type (C/N) */
       %let vtype = %sysfunc(vartype(&dsid, &vnum.));
    %else %do;
       %put NOTE: Variable &var does not exist in &libds;
       %let vtype = %str( );
    %end;
  %end;
  %else %put dataset &libds not opened! (rc=&dsid);

  /* Close dataset */
  %let rc = %sysfunc(close(&dsid));
  /* Return variable type */
  &vtype
%mend;

答案 2 :(得分:1)

在使用vtype函数的数据步骤中,我们还可以从数据集中确定给定变量的类型。

data _NULL_;
  set  sashelp.class (obs=1);
  call symput('numvar',ifc(vtype(sex)='N','YES','NO' ));
run;
%put |&numvar|;

或者,我们可能会将以下声明用于其他目的,而不是电话会议。

if ifc(vtype(sex)='N','YES','NO' )='YES';

相关问题