检查 DS 是否有变量值,如果变量有缺失值则删除该列

Checking whether the DS has variable value if the variable has missing values then drop the column

我正在使用 var= 在宏参数中传递一个 DS,如果其对应的变量具有相同的值但变量具有所有缺失值,则将其删除。

DATA details;
INPUT id name $ dept $ salary;
datalines;
01 John . 10000
02 Mary . 20000
03 Priya . 30000
05 Ram . 25000

;

DATA newdetails;
INPUT var_name $ var_core $;
DATALINES;
id perm
name perm
dept perm
salary req

;

      %macro core_check(inds=,newds=,var_core_val= );
      proc sql noprint;
      select var_name 
      into :varname separated by ' '
      from &newds
      where var_core="&var_core_val.";
      quit;

      %let nvar=&sqlobs;
      %put &varname;

     %do i=1 %to &nvar;
     %let var&i=%scan(&varname,&i);
     proc sql;
     select count(*)
     into :nobs
     from &inds where &&var&i is not missing ;
     %put this = &nobs;
     quit;
     %end;
     %mend;
     %core_check(inds=work.details,newds=work.newdetails,var_core_val=perm); 

这是使用 PROC FREQ 的 NLEVELS 输出检查空变量的一种方法。请注意,ODS table 可能不会根据结果创建 NMissLevels 或 NNonMissLevels 变量。

因此,对于您的问题,我们可以制作一个宏,将要检查的数据集的名称、要创建的数据集以及包含关于哪些变量是可选的元数据的数据集作为其输入。首先获取要检查的变量列表。然后使用 PROC FREQ 检查它们。然后使用数据步骤生成一个带有空变量列表的宏变量。

%macro drop_optional(inds=,newds=,metadata= );
  %local varlist n emptyvars ;
  proc sql noprint;
    select var_name 
     into :varlist separated by ' '
     from &metadata
     where var_core='perm'
    ;
  quit;
  %let n=&sqlobs;
  %if (&n) %then %do;
    ods output nlevels=nlevels;
    proc freq nlevels data=&inds ;
      tables &varlist / noprint ;
    run;
    data nlevels;
      length TableVar  NLevels NMissLevels NNonMissLevels 8;
      set nlevels end=eof;
      nmisslevels+0;
      nnonmisslevels=nlevels-nmisslevels;
      length emptyvars 767;
      retain emptyvars;
      if nnonmisslevels=0 then emptyvars=catx(' ',emptyvars,tablevar);
      if eof then call symputx('emptyvars',emptyvars);
    run;
  %end;
  data &newds;
    set &inds (drop=&emptyvars);
  run;
%mend drop_optional;

那么让我们使用您的示例数据。

data details;
  input id name $ dept $ salary;
datalines;
01 John . 10000
02 Mary . 20000
03 Priya . 30000
05 Ram . 25000
;

data metadata;
  input var_name $ var_core $;
DATALINES;
id perm
name perm
dept perm
salary req
;

并调用宏。

%drop_optional(inds=details,newds=details_new,metadata=metadata);