首页 > 解决方案 > 如果表为空,如何获得等于零的行数而不是什么都没有是SAS

问题描述

我有以下代码,它将行数存储在宏变量内的表中n_vars

data cont_vars;
   set var_list;
   where flg_categorical = 0;
   call symput('n_vars', _n_);
   %put &n_vars;
run;

目前,如果结果表为空,则n_vars解析为空,我希望将其设置为 0,以便%do x = 1 %to &n_vars;稍后在循环中使用它。

标签: sas

解决方案


如果该where语句确实导致在数据集中没有观察到,则以下代码应将n_vars宏变量设置为0

data want;
  if eof then call symputx('n_vars',_n_-1);
  set have end=eof;
  where flg_categorical = 0;
run;

请考虑创建一个Minimal Reproducible Example

data have;
infile datalines delimiter=',';
input x1 flg_categorical;
datalines;                      
1,1
6,2
3,2
;
run;

data want;
  if eof then call symputx('n_vars',_n_-1);
  set have end=eof;
  where flg_categorical = 0;
run;
%put &=n_vars;

结果:

在此处输入图像描述

无论如何,我不知道为什么你会使用%do1 to 0. 当数据集为空时,您可能只想运行另一种步骤。如果是这种情况,我会考虑使用:

%if &n_vars. > 0 %then %do; /* data set is not empty */
...
%end;
%else %do; /* data set is empty */
...
%end;

推荐阅读