SAS 宏



  • /*2 宏Macro*/
    /*2.1 宏变量*/
    %let name1=name;
    %let name2=‘name’;
    proc print data=xie.class;
    where height=67;
    title “&name1 ‘s height is 67.”;
    title2 “&name2 ‘s height is 67.”;
    run;
    
    /*2.2  定义宏*/
    /*参数宏*/
    %macro try(proc,dsn);
    proc &proc data=&dsn;
    run;
    %mend try;
    %try(print,xie.class);
    
    /*无参数宏*/
    %macro plot;/*开始定义宏:PLOT*/
    proc plot;
    plot income*age;
    run;
    %mend plot; /*结束宏的定义*/
    data newdata; /*创建数据集*/
      input  name $ age income;
    cards;
    xie 26 3200
    wang 23 4400
    wu 33 3872
    zhou 19 5400
    meng 22 5580
    ; 
    run;
    %plot/*调用宏,绘制收入关于年龄的散点图*/
    proc print;run;
    data newdata2; /*筛选年龄大于20的记录,建立新数据集*/
    set newdata;
    if age>20;Run;
    %plot/*再次调用宏,绘制收入关于年龄的散点图*/
    proc print;
    run;
    
    /*2.3 宏函数*/
    /*2.4 宏表达式*/
    /*2.5 宏语句*/
    /*2.6 案例*/
    
    /* The Following macro function can find the first position of "exception" in "source" string  */
    %macro indexc(source, exception,delimiter=%str( ));
    /* the leading and tailling blanks will be delete by way of the following statement */
    %let exception =%trim(%left(&exception));
    %local count word result temp;
    %let count=1;
    %let temp=0;
    %let result=0;
    %let word=%qscan(&exception,&count,&delimiter);
    
    %do %while (&word ne);
    	%if (%index(&source,&word) ne 0) %then %do;
    	%let temp=%index(&source,&word);
    	%if (&temp < &result) or (&result = 0) %then %let result=&temp;%end;
    	%let count=%eval(&count+1);
    	%let word=%qscan(&exception,&count,&delimiter);
    %end;
    &result
    %mend indexc;
    
    %indexc(am, I am a teacher,delimiter=%str( ));
    %macro a;
    %local z;
    %let z=%indexc( xie18 - xie6, 1 2 3 4 5 6 7 8 9 0,delimiter=%str( ));
    %put &z;
    %mend a;
    %a;
    
    /*案例二*/
    /*  comma split  */
    %macro split(indata,outdata);
    data &outdata ;
    	set &indata;
    	length str $10;
    	str=trim(left(etiology)); 
    	%do i=1 %to 2;
    		len=length(str); 
    		if trim(left(str))='' then	len=0;
    sep_xie=index(str,","); 
    		if sep_xie=0  then do;
    			if &i=1 then do;
    				etiology_&i=str+0;
    				str='';end;
    			else etiology_&i=.;
    			end;
    if sep_xie=1 then do;
    			etiology_&i=.;str=left(substr(str,sep_xie+1)); 
    		end;
    		if sep_xie>1 then do; 
    		   etiology_&i=left(substr(str,1,sep_xie-1))+0;
    
    str=left(substr(str,sep_xie+1)); 
    		end;
    	%end;
    	rename str=etiology_code;
    	drop len sep_xie;
    run;
    %mend split;
    %split(xie.study,study);
    

登录后回复