2019年7月9日 星期二

SAS MACRO 初步檢查文字變數內是否有亂碼

%macro Garbled(DS=,VAR=,VARn=);
/*===================================================================
作者:JIMMY
最後修改:20190712
DS:輸入要檢查的DATASET
VAR:輸入該DATASET 內要檢查的所有文字變數      | 分隔   如: X | Y
VARn:輸入了多少個VAR
此程式會對DS的VAR進行COMPRESSKEEP英文與數字,然後與COMPRESSKEEP前的DS比對,如壓縮前後不一樣則存到WORK.VAR(變數名稱)
===================================================================*/

%do i = 1 %to  &VARn.; 
    %let VAR&i. = %qscan(%bquote(&VAR.),&i.,%str(|)); 
 data tmp_DS;
  set &DS.;
   &&VAR&i.. = compress(&&VAR&i.. ,'1234567890',"kfs");
    n=_n_;
 run;
 
 data &&VAR&i..  (keep= &&VAR&i..   compressGarbled   n);
  merge &DS.   tmp_DS  (rename=(&&VAR&i.. = compressGarbled));
  if  &&VAR&i..^=compressGarbled;
 run;

 %let open_d = %sysfunc (open( &&VAR&i.. )); 
 %let tmpds = %sysfunc(attrn(&open_d., nobs));
 %let close_d = %sysfunc(close(&open_d.));
 %if &tmpds. < 1 %then %do;
  proc datasets lib=work  mtype=(data view) nolist nowarn;
  delete &&VAR&i.. ;
  run;quit;
 %end;

%end;
proc datasets lib=work  mtype=(data view) nolist nowarn;
delete tmp_DS;
run;quit;

%mend;
%Garbled(DS=test,VAR=X | Y, VARn=2)

例子:
建立一個有亂碼的DATASET
X長度只有1,而DATALINES內有中文的話勢必會變成亂碼
data test ;
length x $ 1.  ;
input X $ ;
Y= 'A';
datalines;
a
b
1

;
run;
%Garbled(DS=test,VAR=X | Y, VARn=2)

執行後,會產生以變數名稱命名的WORK DATASET,如該變數無亂碼則該DATASET不產生(被刪除)。

Related Posts:

  • 產生虛擬變數(dummy variable) 快速生成虛擬變數(dummy variable)  data test; input age aaa y; datalines; 1 1 1 2 2 2 3 3 3 1 4 3 2 5 3 5 5 3 4 5 3 3 1 3 ; run; %dummy(mydata = te… Read More
  • Logistic Regression%macro Deviance_table(data, y, n, old_x) ; /********************************************************************************************************* … Read More
  • 把sas資料集裡的某個值存成巨集變數(macro) 把sas資料集裡的某個值存成巨集變數(macro) 使用 call symputx ("meanx", meanx); 就可以輕鬆存成巨集變數,symputx("巨集變數名稱",  變數名稱)。 巨集變數可以在任一個data step使用。 範例: proc means… Read More
  • proc gtile sas help檔 內容 goptions reset = all device = java noborder; proc gtile data = sashelp.shoes; tile stores tileby = (region subsidiary) / colorvar =… Read More
  • 將SAS報表匯出至外部檔案 可參考這篇(連結) PDF ods pdf file="C:\Users\139869\Desktop\深入解析SAS\test.pdf"; proc print data = sashelp.class; run; ods pdf close; ods pdf fil… Read More

0 意見:

張貼留言