标题: %sysfunc [打印本页] 作者: shiyiming 时间: 2005-10-23 14:02 标题: %sysfunc Foreword: %sysfunc is useful for retrieving information about datasets, changing column attributes and formatting macro variables. Say you wanted to find the total number of observations in a dataset and store that number as a macro variable. You might use something like:
[code:0b162]data _null_;
Set new end=eof;
Count+1;
If eof then call symput('n_obs',count);
Run; [/code:0b162]
The above step would work but unless you are doing some other operations on that dataset it is very inefficient because the entire dataset is being read in. A better way would be to reference the datastep at compile time, which would mean you would not be reading it in eg:
[code:0b162]data _null_;
call symput('n_obs',put(n_obs,5.));
stop;
set new nobs=n_obs;
run; [/code:0b162]
The above code is much better but the equivalent can be done by using a simple one liner with %sysfunc… A simple one liner to get the number of observations in a dataset into a macro variable called &nvars:
[code:0b162]%let nvars=%sysfunc(attrn(open(data name here),nlobs)); [/code:0b162]
More %sysfunc functions
Use the following one liner to get and manipulate the current date and time:
[code:0b162]%put %sysfunc(datetime(),datetime.); [/code:0b162]
Or use it to see if a dataset exists or not.
[code:0b162]%SYSFUNC(EXIST(dataset name here)); [/code:0b162]
The macro below checks if a dataset exists and then runs code depending on the result.
[code:0b162]
%macro exchk(datan);
%if %SYSFUNC(EXIST(&datan)) %then %do;
%put dataset exists;
%end;
%else %do;
%put dataset does not exist;
%end;
%mend exchk; %exchk(dataset name here); [/code:0b162]The macro code below creates a dataset containing column names of a dataset