Showing posts with label sas. Show all posts
Showing posts with label sas. Show all posts

Friday, October 28, 2011

How to create FTP path in SAS program

FILENAME FTPFILE FTP '' LS
HOST = "&FTPHST"
USER = "&FTPUSR"
PASS = "&FTPPAS"
CD = "&FTPCD\&PGMSEC";



DATA _NULL_;
INFILE FTPFILE;
INPUT;
IF _INFILE_ EQ "&PGMMTH" THEN CALL SYMPUT('LEVEL0','Y');
RUN;

FILENAME FTPFILE FTP '' LS
HOST = "&FTPHST"
USER = "&FTPUSR"
PASS = "&FTPPAS"
CD = "&FTPCD\&PGMSEC"
RCMD = "MKD &PGMMTH";


DATA _NULL_;
IF "&LEVEL0" EQ 'N' THEN
DO;
INFILE FTPFILE;
INPUT;
END;
RUN;

Monday, June 6, 2011

SAS Macro: How to Retrieve a Value from a Dataset

Solution 1:

%MACRO Get_data(myDataset=,myLine=,myColumn=,myMVar=);
%GLOBAL &myMVar.;
data _null_;
set &myDataset.;
if _N_ = &myLine. then do;
call symput(symget('myMVar'),&myColumn.);
end;
run;
%MEND Get_data;

Solution 2:

%MACRO Get_data(myDataset=,myLine=,myColumn=,myMVar=);
%GLOBAL &myMVar;
proc sql noprint;
select &myColumn into :&myMVarfrom &myDatasetwhere monotonic() = &myLine;
quit;
%MEND Get_data;
%Get_data(myDataset=tablename,myLine=linenumber,myColumn=colname,myMVar=varname)
%put &varname;

Solution 3: USE SAS I/O functions!

%MACRO Get_data(myDataset,myLine,myColumn);
%global myMvar;
%let dsid=%sysfunc(open(&myDataset.,i));
%let rc=%sysfunc(fetchobs(&dsid, &myLine.));
%if &rc = 0 %then
%let myMvar=%sysfunc(GETVARN(&dsid,%sysfunc(varnum(&dsid,&myColumn))));
/****use getvarc for character variables*****/
%let rc=%sysfunc(close(&dsid));
%MEND Get_data;

MORE SAS CODES

http://www.datasavantconsulting.com/roland/Spectre/maclist2.html

Put all variables except automatic variables in a file

put (_all_)(+0);

Friday, June 3, 2011

Route SAS log and procedure ouput using PROC PRINTTO

PROC PRINTTO is very useful when we try to automate the debugging process of SAS program.

LABEL= provide a description for a SAS log or procedure output stored in a SAS catalog entry
LOG= route the SAS log to a permanent external file or SAS catalog entry
LOG= and PRINT= with same destination combine the SAS log and procedure output into a single file
NEW= replace the file instead of appending to it
PRINT= route procedure output to a permanent external file or SAS catalog entry

Using a PROC PRINTTO statement with no options closes any files opened by a PROC PRINTTO statement points both the SAS log and SAS procedure output to their default destinations.

Example:

options nodate pageno=1 linesize=80 pagesize=60 source;

proc printto log='log-file';
run;

data numbers;
input x y z;
datalines;
14.2 25.2 96.8
10.8 51.6 96.8
9.5 34.2 138.2
8.8 27.6 83.2
11.5 49.4 287.0
6.3 42.0 170.7
;

proc printto print='output-file' new;
run;proc print data=numbers;
title 'Listing of NUMBERS Data Set';
run;

proc printto;
run;

Tuesday, May 31, 2011

ALL THE FILES, PLEASE

A number of ways to read multiple files in one data set.


First, just list the files in a series of DATALINES
in the DATA step.
DATA one;
LENGTH fil2read $ 40;
INPUT fil2read $;
INFILE dummy FILEVAR=fil2read
END=done;
DO WHILE (NOT done);
INPUT lastn $ firstn $
hiredate : mmddyy8.
salary;
OUTPUT;
END;
DATALINES;
D:\Infile\emplist.dat
D:\Infile\emplist1.dat
D:\Infile\emplist2.dat
D:\Infile\emplist3.dat
D:\Infile\emplist4.dat
RUN;



Be careful to set up the DO loop so that the DATA step never gets to the End-Of-File marker on any file. Using the END= option on the second INFILE statement sets up a temporary variable (done) which will register 0 (not the last record) or 1 (the last record) for each raw data line read
in from each file. This is necessary since, if SAS reads in any End-of- File marker, the DATA step closes.
By testing for DONE at the top of the loop (DO WHILE), and exiting the DO loop after the last line of every file, we ensure that we never hit the end-of-file for all files read in. This remains true even for empty files.


A SAS Dataset can be used to store the names of the files and would be called using a SET statement.

DATA one;
set two;
INFILE dummy FILEVAR=fil2read
END=done;
DO WHILE (NOT done);
INPUT lastn $ firstn $
hiredate : mmddyy8.
salary;
OUTPUT;
END;
RUN;



Finally, it’s possible to read in filenames dynamically, using a FILENAME with the Pipe option. This is useful when all of the files are in the same directory. With the PIPE keyword, the FILENAME statement can take an operating system command in quotes, and accept the result as valid input. Unfortunately, this is not available on Mainframe operating systems.


FILENAME indata PIPE "dir D:\Infile\*.dat /b";
DATA test;
LENGTH fil2read $40;
INFILE indata MISSOVER;
INPUT fil2read $;
fil2read="d:\infile\"fil2read;
INFILE dummy FILEVAR=fil2read END=done;
DO WHILE(NOT done);
INPUT lastn $ firstn $ hiredate : mmddyy8. salary;
OUTPUT;
END;
RUN;



The information returned from the FILENAME statement is a list of all files in D:\Infile with a .DAT type. One can specify all files, or (as above) specific files. The DATA step can use this information with one INFILE statement and then use the information to read the files by
applying it to a FILEVAR= option on a second INFILE statement.

One limitation is that the Windows command (DIR) returns only the names of the files without the pathnames. So the fil2read variable needs to be augmented with the pathname in an
assignment statement. fil2read="d:\infile\"fil2read;
In UNIX, a similar FILENAME statement would read:

FILENAME indata PIPE "ls -l /Infile/*.dat /b";

The UNIX ls command returns a fully qualified path and filename.

MISSOVER, TRUNCOVER and PAD

MISSOVER was originally created to be used in conjunction with PAD and works effectively and well in most situations. However, this can be a CPU intensive process when reading an extremely large file.

STOPOVER is a good tool for checking code and raw data when dealing with large, potentially messy files, since it forces the DATA step to stop the first time it finds a short line.

TRUNCOVER was developed later than the MISSOVER and PAD options, and deals admirably with not only short lines but with short values. TRUNCOVER is more also efficient since it doesn't require the extra "padding".

Thursday, April 14, 2011

SAS Enhanced Editor - KeyBoard Shortcuts that YOU Should Know

Here are a few shortcuts and their descriptions:

1) Comment selected section of code with Line Comments press: CTL+/
2) Uncomment selected section that has Line Comments press: CTL+SHIFT+/
3) Convert selected section to lowercase press: CTL+SHIFT+L
4) Convert selected section to uppercase press: CTL+SHIFT+U
5) Indent selected section press: TAB
6) Un-indent selected section press: SHIFT+TAB
7) To move curser to the matching DO/END statement press:
a) ALT+[
b) ALT+]
c) ALT+9
d) ALT+0
8) Delete trailing white space from selected text(from line if not selected) press: CTL+SHIFT+W
9) Collapse all folding blocks press: ALT+CTL+ -
10) Expand all folding blocks press: ALT+CTL+ +
11) Go to line number press: CTL+G

PROC SQL V.S. DATA STEP

BENEFITS/ADVANTAGES

The following list of benefits is not intended to be complete as much as a more general comment on issues of which the beginning SAS programmer should be aware. The lists are in no particular priority order.

PROC SQL
♦ PROC SQL provides the combined functionality of the DATA step and several base SAS procedures.
♦ Less complex and lengthy, but not as legible, code can be written in PROC SQL.
♦ PROC SQL code may execute faster for smaller tables.
♦ PROC SQL code is more portable for non-SAS programmers and non-SAS applications.
♦ PROC SQL processing does not require explicit code to presort tables.
♦ PROC SQL processing does not require common variable names to join on, although same type and length are required.
♦ By default, a PROC SQL SELECT statement prints the resultant query; use the NOPRINT option to suppress this feature.
♦ Knowledge of relational data theory opens the power of SQL for many additional tasks.
♦ PROC SQL processing forces attention to resultant data set structures, as SQL is unforgiving of "errors of design".
♦ Efficiencies within specific RDBMS are available with Pass-thru code for the performance of joins.
♦ Use of aliases for shorthand code may make some coding tasks easier.

NON-SQL BASE SAS
♦ DATA step set operators can handle more data sets at a time than PROC SQL outer joins.
♦ Non-SQL techniques can open files for read and write at the same time.
♦ Customized DATA step report writing techniques (DATA _NULL_) are more versatile than using PROC SQL SELECT clauses.
♦ The straightforward access to RDBMS tables as if they were SAS data sets negates the need to learn SQL constructs.
♦ Input of non-RDBMS external sources is easier.

Wednesday, April 13, 2011

A Mass Mailing Macro

%macro emailit(mindsn=,mletter=letter,mfobs=1, mlobs=999999,msubject=,mattach=);
data letter; /* put letter in SAS file */
infile cards4 truncover; /* from cards below */
input @1 text $char100. ;/* input text field */
cards4; /* type letter text below */

Dear SAS User,
We are pleased to announce our latest class,
"Exploiting SAS ODS".
See you there.
Thank you,
Steven First
;;;; /* end of letter text */
run; /* end of step */

data _null_; /* go thru mail list and */
/* put all emails>mac vars*/
set &mindsn(firstobs=&mfobs obs=&mlobs) end=eof;
call
symput('memail'!!left(put(_n_,5.)),compress(email));
if eof then
call symput('mtotem',left(put(_n_,5.)));
run;

/****************************************************/
/* Loop through all the mac vars and send letter */
/****************************************************/
%do i=1 %to &mtotem;
filename emailf email "&&memail&i"
subject="&msubject";
data _null_;
file emailf attach="&mattach";
set &mletter;
put @1 text;
run;
%end;
%mend emailit;


/****************************************************/
/* Invoke the macro. */
/****************************************************/
%emailit(mindsn=mail.select, /* mail dataset */
mletter=letter, /* lett ds with text */
mfobs=1, /* 1st obs to send */
mlobs=1, /* last obs to send */
msubject=%bquote(Presenting our newest course
"Exploiting the SAS Output Delivery System"),
mattach=ods1.doc
;

Delete all global macro variables

To delete all global user macro variables where you don’t have to specify the variable names, a pair of data steps can be used to delete all variables found:

data macvars; /* build ds for mac vars */
set sashelp.vmacro; /* names in dict table */
where scope='GLOBAL'; /* only keep globals */
run; /* end of step */

data _null_; /* another step */
set macvars; /* read above, and delete*/
call execute('%symdel '!!trim(left(name))!!';');
run; /* end of step */

Quoting functions in MACRO

You may know %str and %nrstr, which are compilation phase quoting functions. But do you know other quoting functions in execution phase?

Execution Functions
There are functions cause the macro facility to treat items as text during macro execution as well. %QUOTE and %NRQUOTE operate at execution time and remove meaning of most characters in the result of the macro call. %BQUOTE and %NRBQUOTE should be used if the value contains unmatched quotes or parentheses.

Examples:

%macro getst(state,employee);
%if quote(&state) = %str(NE) %then
%do;
%let longst=Nebraska;
%end;
%put hello &employee from &longst;
%mend;
%getstate(NE,O’brien)


Functions to Prevent Resolution

%SUPERQ is a function that will prevent starting any resolution of macro variables. This is most needed in windowing operations such as SAS/AF®, %WINDOW, or SAS/IntrNet® screens, or after CALL SYMPUT if there is any chance the input value could contain an
ampersand or percent sign. Other functions do not work as well in this case, and would issue warnings and recursion messages.

Example:

data _null_;
call symput('mv1','Bob&Fred %macro report');
run;
%let mv2=%superq(mv1);
%put mv2=&mv2;
The Result:
mv2=Bob&Fred %macro report


Unquoting

The effects of quoting can be removed if desired by the %UNQUOTE function. In the example below var2 is not resolved but using %UNQUOTE later allows the resolution to take place.
Example:

%let mv1= hallo;
%let mv2=%nrstr(&mv1);
%let mv3=%unquote(&mv2);
%put mv1=&mv1 mv2=&mv2 mv3=&mv3;


The Result:

mv1=hallo mv2=&mv1 mv3=hallo;

Tuesday, April 12, 2011

MACRO - DATA Step Interfaces

There are eight interfaces that interact with macros when DATA steps execute.

CALL EXECUTE routine: resolves argument and executes macros immediately and generated code at next step boundary

RESOLVE function : resolves text expression at execution

CALL SYMDEL routine : deletes a macro variable

SYMEXIST function : test for macro variable existence

SYMGLOBL function : tests for global scope

SYMLOCAL function : tests for local scope

CALL SYMPUT routines : assigns DATA step values to macro variables

-----------------------------------------------------------------------------

In particular, CALL EXECUTE is very useful when you want to generate code in data step.

EXECUTE::
if argument is single quoted string, resolves during data step execution.
If double quoted string and a macro element, resolves during data step compile.
If a DATA step variable, must contain a text expression or SAS statement to generate
can also be a expression that is resolved to a macro text expression or SAS statement.
CALL EXECUTE can be a good way to avoid complicated macros.

A Call Execute Example
Generate a PROC PRINT for each county in our file.

data pass2;
set countydt;
by countynm;
if first.countynm then ctyobs=0;
ctyobs+1;
if last.countynm then
call execute('PROC PRINT DATA=COUNTYDT; ' || 'WHERE COUNTYNM="' || countynm || '";' ||
'OPTIONS PAGENO=1;' ||
'TITLE "REPORT FOR COUNTY ' || countynm || '";' ||
'FOOTNOTE "TOTAL OBSERVATION COUNT WAS ' || put(ctyobs,2.) || '";' ||
'RUN;'
);
run;


----------------------------------------------------------------

The RESOLVE Function

Resolves the value of a text expression during DATA step execution.
Syntax:

variable=RESOLVE(argument);
Notes:
if argument is single quoted string, resolves during data step execution.
If double quoted string and a macro element, resolves during data step compile.
RESOLVE allows you to delay resolution until data step executes. For example: to use macro variables created in data step.

RESOLVE Comparisons
RESOLVE resolves values during DATA step execution, where macro references resolve during scan.
RESOLVE accepts a wider variety of arguments than SYMGET(one variable) does.
When a macro variable contains additional macro references, RESOLVE will resolve, but SYMGET does not.
If argument is non-existent, RESOLVE returns unresolved reference, SYMGET returns a missing value.
Because it’s more flexible, RESOLVE takes slightly more resources.

A RESOLVE Example

%let event=Holiday;
%macro mdate;
4th of July
%mend mdate;
data test;
length var1-var3 $ 15;
when='%mdate';
var1=resolve('&event'); /* macro variable reference */
var2=resolve('%mdate'); /* macro invocation */
var3=resolve(when); /* DATA step var with macro call */
put '*** ' var1= var2= var3=;
run;

*** var1=Holiday var2=4th of July var3=4th of July

SAS steps boundaries

In case you see this question in a interview, :)

DATA ENDSAS
PROC LINES
CARDS LINES4
CARDS4 PARMCARDS
DATALINES QUIT
DATALINES4 RUN

Tuesday, April 5, 2011

THE _NULL_ DATA STEP

The _NULL_ DATA step is a specialized case of the DATA step. When you use the _NULL_ key word, the DATA statement processes all statements within the DATA step without data set creation.
Some of the uses of DATA _NULL_ are:
***To create customized reports with and without ODS. The reports can be routed to the Output window, directly to printer, to an external file, or any destination that can be defined by the FILE and FILENAME statement.
***To create macro variables based on values obtained from an input SAS data set or external file.
***To create ASCII data (flat) files for importing into MS Excel MS Access or other programs and databases.
***To execute special functions or call routines available within the DATA step, such as CALL EXECUTE.

Sunday, April 3, 2011

SAS debug system option

System-level options. These options control the
amount of diagnostic output you receive, and the
source statements that are displayed in the Log. They
also tell the SAS Supervisor how to react to abnormal
conditions – that is, whether a particular event (such
as an unknown format) should be considered an error.
---------------------------------------------------------------------
Category Options
---------------------------------------------------------------------
print source in Log ECHOAUTO, SOURCE, SOURCE2

messages in Log MSGLEVEL, NOTES, DETAILS, PRINTMSGLIST

invalid references BYERR, DATASTMTCHK, DKRICOND,
DKROCOND, DSNFERR, ERRORABEND,
ERRORCHECK, FMTERR, VNFERR

reaction to errors CLEANUP, ERRORABEND, ERRORS, INVALIDDATA

data set creation MERGENOBY, REPEMPTY, REPLACE, WORKTERM

using observations FIRSTOBS, OBS, WHERE

option settings OPLIST

Other MISSING functions

NMISS: counts the number of missing values among its arguments.

CALL MISSING: set any variables in its argument to missing whether character or numeric.

N : to count the number of non-missing values. If all values are missing then the N function will be zero.

MISSING(CATS(CHAR1,CHAR2,,,CHARN)): check if all char arguments are missing.

MISSING OPTION

You have just printed out a listing of the number of Adverse Events for each patient in a drug study. Since no data exist for patients without occurrences, the listing shows a ‘.’ for these patients, even though it should say ‘0’. Now you could write a DATA step to change the missing values to zero, or you could format the value to zero. Since you don’t need this information anywhere else, why not just change the global option:

option missing = '0';

The MISSING option allows you to change the character displayed when missing numeric data is encountered. So instead of ‘.’ in our output, we now have ‘0’ displayed. In fact, all displays of the data after the invocation of this option will be set to the new value. So remember to change the option back after your output statements or you
might get unexpected results later in your program.

MISSING STATEMENT

You are requested to generate a report on all subjects in a study that had a missing value for their birth dates. So you write a DATA step to subset the data:

data MissingBirth;
set Raw;
if birthdate = . then output;
run;


This step is simple and seemingly effective code. However, the person who created Raw used special missing character to account for the different missing (e.g. .A for adopted and no original record, .Q for interviewer forgot to ask, etc.). So you still have missing birthdates in your output data. Rewriting the IF statement as

if birthdate <= .Z then output;

would solve this problem. Another research site sends you a new set of Raw data and you run your subsetting program. Of course, it doesn’t work. This time the researchers entered the dates as text strings. So you could now write the IF statement as

if birthdate = ' ' then output;

But you have no way of knowing what kind of data you will get in the future. To cover all bets, you could write the IF statement as

if missing(birthdate) then output;

Friday, April 1, 2011

Efficient techniques for accessing large datasets

Using Keep, Drop and Where options.
Data restructuring.
Remote Processing.
Compressing SAS data sets
Using Index’s.
Using SAS Views.
Using SQL.
Source Control language (Source Component
Language).
Using MDDB’s.
Using HOLAP.

To read details
http://www2.sas.com/proceedings/sugi25/25/dw/25p115.pdf

DO OVER

An unadvertised form of the iterative Do group is the Do Over. It processes arrays just like the Index Variable group, but without having to specify the Index Variable or its control value. The total number of elements in the array is passed from the DATA Step to the Do Over. The coding forms below access their arrays exactly the same way: from element one (1) through element five (5).
Do Over Index Variable
Array Test X1-X5 (1,3,5,7,9);
Do over test;
Put test(_I_)=;
End;
Array Test (5) X1-X5 (1,3,5,7,9);
Do J = 1 to 5;
Put test(j)=;
End;
Both of these examples use the initial values option to create five variables, X1 – X5, and load numeric values to those variables.
The Do Over syntax is no longer documented by SAS, but it is still available since it was released in earlier versions of Base SAS. Info on its usage can be found in the SAS Global Forum proceedings at http://support.sas.com/events/sasglobalforum/previous/online.html. Just be aware that it can only be used with implicitly subscripted arrays, which is why Test doesn’t have a subscript in that example. Also, implicit arrays have the step-generated counter of _I_.
The benefit of the Do Over form can now be obtained with the Dim function, which returns the number of elements in an array. The ‘Do Over Test;’ shown above would be changed to ‘Do J = 1 to Dim(test);’ and the ‘Put test(_I_)=;’ would become ‘Put test(j)=;’.