Transcription of Beginning Tutorials Paper 57 Introduction to SAS …
1 Paper 57 Introduction to SAS FunctionsNeil Howard, Independent Consultant, Charlottesville, VAAbstractA FUNCTION returns a value from a computation orsystem manipulation that requires zero or morearguments. And, like most programming languages, theSAS System provides an extensive library of built-in functions. SAS has more than 190 functions for a varietyof programming tasks. This tutorial will cover the syntaxfor invoking functions, an overview of the functionsavailable, examples of commonly used functions, selectedcharacter handling and numeric functions, and sometricks and applications of functions that will surprise Down a FUNCTION - SyntaxGiven the above definition of a function, the syntax andcomponents should be examined.
2 A function recognizedin a SAS statement by the use of a function name,followed immediately by function argument(s), separatedby commas, and enclosed in a function requiring two arguments the syntax is asfollows:FUNCTIONNAME(argument-1, argument-2) where the arguments are: constants variables expressions other functionsSeveral functions take no arguments, in which case a nullset of parentheses is required. For instance, the TODAY function returns today s date from the system clock,requiring no arguments:DATA NEW; X = TODAY() ; PUT X= X MMDDYY8.
3 ;RUN;X= 01/18/99;The variable X is returned as the numeric SAS daterepresentation and should be displayed with a Down a FUNCTION - ArgumentsThe arguments to any given function can be variables,constants, expressions, and/or other = SQRT(9562) ;variableY = ABS(BAL) ;expression Z = MAX((BAL-DEBIT),(NEWCAR+GAS)) ;function Q = ABS(SQRT(ABC-64)) ;In these examples, X is the square root of 9562, Y wouldbe the absolute value of the variable BAL, Y contains thevalue of the larger of the two expressions, and Q is theabsolute value of the square root of ABC minus 64.
4 Asimilar numeric function, MIN, returns the value of thelowest of its nonmissing arguments. The SUM functionrequires at least two arguments and returns the sum ofthe nonmissing = SUM( X, Y, Z ) ;Use of the keyword OF gives the user the flexibility toinclude variable lists, array elements and other shortcuitsfor referencing variable = SUM( OF TEMP1 - TEMP24 );B = SUM( OF TEMP1 TEMP2 TEMP3 );C = SUM( OF TMPARRAY {*} );D = SUM( OF _NUMERIC_ );E = SUM( OF TEMP1 -- TEMP24 );In the examples above, A gives you the total of 24consecutive temperature readings where numberedvariable names were used.
5 Using no commas, you cansum three temperature value to calculate B. When anarray named TMPARRAY has been defined, you canpass the elements to the SUM function to get C. Allnumeric variables in the program data vector (PDV) areadded to produce D, and E is derived by adding allvariables in placement order in the PDV between andincluding TEMP1 and of FUNCTIONSThe library of functions contains several categories offunctions, including: arithmetic (like ABS, MIN, MAX,SQRT), array ( , DIM), character handling ( , LEFT,RIGHT, SUBSTR, REVERSE, LENGTH), date and time( , TODAY, JULDATE, MDY, INTCK, TIMEPART),financial ( , MORT, NPV, SAVING), mathematical ( ,LOG, EXP), probability ( , POISSON, PROBCHI),quantile, random number ( , NORMAL, UNIFORM), Beginning Tutorialssample statistics ( , MEAN, MIN, MAX, STD, NMISS),special functions ( , LAG, PUT INPUT)
6 , state and zipcode, trigonometric and hyberbolic, and truncation(ROUND, CEIL, FLOOR). Chapter 11 of the SASL anguage manual for the complete list and vs. PROCEDURESSome functions that are commonly used compute the sum(SUM), arithmetic mean (MEAN), variance (VAR),standard deviation (STD), minimum value (MIN), andmaximum value (MAX). These functions compute thesame simple descriptive statistics available in PROCMEANS, however. The fundamental difference betweenfunctions and procedures is that a function expects theargument values to supplied across an observation in aSAS data set.
7 Procedures expects one variable value Data SetV A R I A B L E SOBSERVATIONSF U N C T I O N SPROCEDURESThe following code calculates the average temperatureper day using the MEAN function executed for eachobservation. The resulting new data set and new variableAVGTEMP are passed to PROC MEANS to calculate theaverage temperature per month. Note that, not only if thevariable list notation used as a shortcut for specifying thefunction arguments, the OF keyword prevents theargument specification from being misinterpreted as theexpression T1 minus average ; set temp ; avgtemp = mean( of T1 - T24 ) ;run ;proc sort ; by month ;run ;proc means ; by month ; var avgtemp ;run.
8 Missing ValuesRemembering that functions must be used in SASstatements and that missing values propogate, be awareof how each function handles missing values. Rely on theSAS Language manual specs and your own programmatictesting code to validate your intended example, the MEAN function will return the arithmeticaverage for the nonmissing arguments, using the numberof nonmissings as the denominator. Likewise, SUM totalsall the nonmissing arguments. However, if all thearguments are missing, the total will be missing, NOTzero, which could effect later calculations in your force a zero total, include the constant on yourcalculation:X = SUM( A,B,C,D,E,F,0 );Y = SUM( OF T1 - T24, 0 );The functions NMISS and N allow you to determine thenumber of missing values and nonmissings, respectively,in the argument = NMISS( A,B,C,D,E,F ); * # of missings;B = N( L,M,N,O,P ); * # of nonmissings.
9 Length of Target VariablesTarget refers to the receiving variable on the left side ofthe equal sign in the SAS statement where a function isused on the right to calculate or otherwise produce aresult. The default length for a numeric target is 8;however, for some character functions, the default lengthof the target variable is 200 or the length of the sourcevariable (argument). The SCAN function returns a givenword from a character string using default and NEW ; X = ABCDEFGHIJKLMNOPQRSTUVWXYZ ; Y = SCAN(X, 1, K ) ; PUT Y= ;RUN ;Y = ABCDEFGHIJIn the example above, the variable X has a length of 26,and the SCAN function is searching X for the first word using K as the delimiter.
10 A PROC CONTENTS run on thedata set NEW will show the length for Y in the descriptoras is a commonly used character handling functionthat extracts a string from an argument or replacescharacter value contents. The function takes threearguments: the source (or argument), the starting positionin constant or variable form, and the length of thesubstring expressed as a constant or NEW ; SET OLD ; ** CONTAINS A B C; X = SUBSTR( A, 23, 4 ) ; Y = SUBSTR( A, B, 3 ) ; Beginning Tutorials Z = SUBSTR( A, 9, C ) ; PUT A= B= C= X= Y= Z= ;RUN.