SAS Functions

Embed Size (px)

Citation preview

  • 5/21/2018 SAS Functions

    1/40GSK Knowledge Centre @ 2011

    Overview

    This presentation will cover the syntax for invoking some of thefunctions, an overview of the functions available, examples ofcommonly used functions.

    Helps to understand some of the basic & frequently used SAS

    functions.

    To write the new SAS Programs or to understand the existing SAScodes.

    To make changes to the available SAS code in order to get thedesired output.

  • 5/21/2018 SAS Functions

    2/40GSK Knowledge Centre @ 2011

    Table of Contents

    DefinitionFunctions Classification

    Arithmetic Functions:Abs ,Hbound , Lbound , Dim, Mod, Sign

    Character Functions: Lowcase , Upcase & Propcase, Compress & Compbl,Find & Findc, Index, Indexw, Indexc, Substr,CAT,CATT & CALL CATT,CATX & CALL CATX,CATS &

    CALL CATS, Scan,Translate , Transwrd , Length,Count & Countc

    Date & Time Functions: Date, Datejul, Datepart, Datetime, Day, INTCK,INTNX, Today, Mdy, Month, Quarter, Weekday,Year.

  • 5/21/2018 SAS Functions

    3/40GSK Knowledge Centre @ 2011

    FUNCTION

    Function returns a value from a computation or system manipulationthat requires zero or more arguments. And, like most programminglanguages, the SAS System provides an extensive library of built-infunctions. SAS has more than 200 functions for a variety ofprogramming tasks.

    Broadly Functions can be classified under following heads:

    Arithmetic ,Character, Date and Time , Financial, Mathematical ,

    Probability , Quantile , Random Number, Sample Statistic,

    State & ZIP Code, Trigonometric and Hyperbolic, Truncation

    We will cover some of frequently used functions such as

    arithmetic, character and Date.

  • 5/21/2018 SAS Functions

    4/40GSK Knowledge Centre @ 2011

    Arithmetic Functions

    Function Name Description Syntax &

    Example

    Output

    ABS Returs absolutevalue

    Abs(argument)eg: abs(-100)

    100

    Hbound Returns upperbound of an array

    HBOUND(array-name)

    Eg: array big{5}weight sex heightstate city; do i=1to hbound(big5);

    5

    Lbound Returns Lower

    bound of an array

    LBOUND(arra

    y-name)Eg:array big{2:6}weight sex heightstate city; doi=lbound(big) tohbound(big);

    2

  • 5/21/2018 SAS Functions

    5/40GSK Knowledge Centre @ 2011

    Arithmetic Functions

    Function Name Description Syntax &Example

    Output

    MOD Returns theremainder fromthe division of thefirst argument bythe secondargument,

    MOD (argument-1, argument-2)

    x1=mod(10,3);

    X1=1.0000

    SIGN Returns the signof a value.Sign functionreturns followingvalues0 then 1

    SIGN(argument)

    x=sign(-5);

    x=sign(5);x=sign(0);

    X=-1X=1X=0

  • 5/21/2018 SAS Functions

    6/40GSK Knowledge Centre @ 2011

    Arithmetic Functions

    DIM: Returns the number of elements in an array.Syntax: DIM(array-name)

    n specifies the dimension, in a multidimensional array, for whichyou want to know the number of elements. If no n value isspecified, the DIM function returns the number of elements in the

    first dimension of the array. array-name specifies the name of an array that was previously

    defined in the same DATA step. This argument cannot be aconstant, variable, or expression.

    Example :

    DIM returns a value of 5. Therefore, SAS repeats the statements inthe DO loop five times.

    array big{5} weight sex height state city; do i=1 to dim(big);

  • 5/21/2018 SAS Functions

    7/40GSK Knowledge Centre @ 2011

    Character Functions

    Functions That Change the Case of Characters:Name Purpose Syntax Example Output

    Lowcase To change all letters tolower case.

    Lowcase(Character_vale)

    Status=CLowcase(Status)

    c

    Upcase To change all letters toupper case.

    Upcase(Character_vale)

    Detprod=seretideUpcase(detprod)

    SERETIDE

    Propcase To change all letters toproper case. Propcase(Character_vale) surname=DAVIDPropcase(surname)

    David

  • 5/21/2018 SAS Functions

    8/40GSK Knowledge Centre @ 2011

    Character Functions

    Functions That Remove Characters from Strings

    Name Purpose Syntax Example Output

    Compbl Compbl (compress

    blanks) can replacemultiple blanks with asingle blank.

    Compbl(Character_valu

    e)

    Rep_name = D

    LevisCompbl(Rep_name)

    D Levis

    Compress To remove specified

    characters from acharacter value.

    Compress(character-

    value )

    Product=Travel_

    Health_VaccinesCompress(Product,_")

    TravelHealthVaccines

  • 5/21/2018 SAS Functions

    9/40GSK Knowledge Centre @ 2011

    Character Functions

    FIND :To locate a substring within a string. With optional arguments,you can define the starting point for the search, the direction of thesearch, and ignore case or trailing blanks.

    Syntax: FIND(character-value, find-string )

    Examples:

    Rep_name = John Davidson

    Surname =John

    Function OutputFIND(Rep_name , Surname ) 1

    FIND("abcxyzabc","abc",4) 7

  • 5/21/2018 SAS Functions

    10/40GSK Knowledge Centre @ 2011

    Character Functions

    FINDC: To locate a character that appears or does not appear within astring. With optional arguments, you can define the starting point for thesearch, the direction of the search, to ignore case or trailing blanks, or tolook for characters except the ones listed.

    Syntax: FINDC(character-value, find-characters )

    Examples

    STRING1 = "Apples and Books

    STRING2 = "abcde

    Function Output

    FINDC(STRING1, STRING2) 5

    FINDC(STRING1, STRING2, 'i') 1

    FINDC(STRING1,"aple",'vi') 6

  • 5/21/2018 SAS Functions

    11/40GSK Knowledge Centre @ 2011

    Character Functions

    INDEXC: To search a character string for one or more characters.

    Syntax:INDEXC(character-value, 'char1','char2','char3,...)

    Note:The INDEXC function returns the first occurrence of any of thechar1 ,char2, etc., values in the string. If none of the characters is

    found, the function returns a 0.Examples

    Org_name = Singh & Singh Pharmacy

    Function Output

    INDEXC(Org_name ,P',a',n') 3 (position of the n")INDEXC(Org_name , &') 7 (position of the &")

    INDEXC(Org_name ,Sin') 3 (position of the n")

    Note: It makes no difference if you list the search characters as 'ABC' or

    'A','B','C'.

  • 5/21/2018 SAS Functions

    12/40GSK Knowledge Centre @ 2011

    Character Functions

    INDEXW: To search a string for a word, defined as a group of lettersseparated on bothends by a word boundary (a space, the beginningof a string, end of the string).

    Note:that punctuation is not considered a word boundary.

    Syntax: INDEXW(character-value, find-string)

    Examples

    Org_name = Singh & Singh Pharmacy

    Function OutputINDEXW(Org_name,Singh") 1 (the word Singh")

    INDEXW(Org_name,mac") 0 (not a word)

    INDEXW("ABABAB","AB") 0 (no word boundaries around "AB")

  • 5/21/2018 SAS Functions

    13/40GSK Knowledge Centre @ 2011

    Character Functions

    SUBSTR : To extract part of a string. When the SUBSTR function isused on the left side of the equal sign, it can place specifiedcharacters into an existing string

    Syntax: SUBSTR(character-value, start )

    Character - value is any SAS character expression.Start - is the starting position within the string.

    Length - if specified, is the number of characters to include in the

    substring. If this argument is omitted, the SUBSTR function will return all

    the characters from the start position to the end of the string.If a length has not been previously assigned, the length of the resulting

    variable will be the length of the character-value.

  • 5/21/2018 SAS Functions

    14/40GSK Knowledge Centre @ 2011

    Character Functions

    Examples:STRING = "ABC123XYZ

    Function Output

    SUBSTR(STRING,4,2) "12

    SUBSTR(STRING,4) "123XYZ

    SUBSTR(STRING,LENGTH(STRING)) "Z" (last character in thestring)

  • 5/21/2018 SAS Functions

    15/40GSK Knowledge Centre @ 2011

    Character Functions

    CALL CATS: To concatenate two or more strings, removing both

    leading and trailing blanks before the concatenation takes place. Tohelp you remember that this call routine is the one that strips theleading and trailing blanks before concatenation, think of the S at theend of CATS as "strip blanks.

    Syntax: CALL CATS(result, string-1 )result is the concatenated string. It can be a new variable or, if it is an

    existing variable, the other strings will be added to it. Be sure that the

    length of result is long enough to hold the concatenated results. If not,

    the resulting string will be truncated, and you will see an error message

    in the log.

    string-1 and string-n are the character strings to be concatenated.

    Leading and trailing blanks will be stripped prior to the concatenation.

  • 5/21/2018 SAS Functions

    16/40GSK Knowledge Centre @ 2011

    Character Functions

    CALL CATT:To concatenate two or more strings, removing only

    trailing blanks before the concatenation takes place. To help youremember this, think of the T at the end of CATT as "trailing blanks" or"trim blanks.

    Syntax: CALL CATT(result, string-1 )

    result is the concatenated string. It can be a new variable or, if it is an

    existing variable, the other strings will be added to it. Be sure that

    the length of result is long enough to hold the concatenated

    results. If not, the program will terminate and you will see an error

    message in the log. string-1 and string-n are the character strings to be concatenated.

    Trailing blanks will be stripped prior to the concatenation.

  • 5/21/2018 SAS Functions

    17/40GSK Knowledge Centre @ 2011

    Character Functions

    CALL CATX:To concatenate two or more strings, removing both

    leading and trailing blanks before the concatenation takes place, andplace a single space, or one or more characters of your choice,between each of the strings. To help you remember this, think of the Xat the end of CATX as "add extra blank.

    Syntax: CALL CATX(separator, result, string-1 )separator is one or more characters, placed in single or double

    quotation marks, that you want to use to separate the strings

    result is the concatenated string. It can be a new variable or, if it is an

    existing variable, the other strings will be added to it. Be sure that the

    length of result is long enough to hold the concatenated results. If

    not,the program will terminate and you will see an error message in the

    log. single blank will be placed between the strings.

  • 5/21/2018 SAS Functions

    18/40GSK Knowledge Centre @ 2011

    Character Functions

    Function Output

    CALL CATS(RESULT, Code,Year)CALL CATS(RESULT , Product,Code,Year)CALL CATS(RESULT, Previous,code)

    MAT2012SeretideMAT2012PreviousMAT"

    CALL CATT(RESULT, Code,Year)CALL CATT(RESULT , Product,Code,Year)

    CALL CATT(RESULT, Product,yrmo)

    MAT2012 SeretideMAT2012Seretide 201201

    CALL CATX(_ ", RESULT, Code,Year)

    CALL CATX(_", RESULT, Product,yrmo)

    CALL CATS( ,RESULT, Previous,code)

    MAT_2012Seretide_201201Previous MAT"

    Example:

    Code=MAT (no blanks)Product= Seretide (leading blanks)Year=2012 (trailing blanks)Yrmo= 201201 (leading and trailing blanks)

  • 5/21/2018 SAS Functions

    19/40

    GSK Knowledge Centre @ 2011

    Character Functions

    CAT: To concatenate (join) two or more character strings, leavingleading and/or trailing blanks unchanged. This function accomplishesthe same task as the concatenation operator (||).

    Syntax:CAT(string-1, string-2 )

    Note:It is very important to set the length of the resultingcharacter string, using a LENGTH statement (or other method),before using any of the concatenation functions.

    Otherwise, the length of the resulting string will default to 200.

  • 5/21/2018 SAS Functions

    20/40

    GSK Knowledge Centre @ 2011

    Character Functions

    Name Syntax Purpose

    CATS Syntax: CATS(string-1,string-2 )

    To concatenate (join) two or morecharacter strings, stripping bothleading and trailing blanks.

    CATT Syntax: CATT(string-1,string-2 )

    To concatenate (join) two or morecharacter strings, stripping onlytrailing blanks.

    CATX Syntax: CATX(separator,string-1, string-2 )

    To concatenate (join) two or morecharacter strings, stripping bothleading and trailing blanks andinserting one or more separatorcharacters between the strings.

    Other Concatenate Functions

  • 5/21/2018 SAS Functions

    21/40

    GSK Knowledge Centre @ 2011

    Character Functions

    Syntax Output

    CAT(Code,Product)CAT(Product,Code,Year) CAT(Latest,Code)

    MAT Seretide SeretideMAT2012LatestMAT

    CATS(Code,Product)CATS(Product,Code,Year) CATS(Latest,Code)

    MATSeretideSeretideMAT2012LatestMAT

    CATT(Year,Product)CATT(Year,Code) CATT(Product,Yrmo)

    2012 Seretide2012MAT Seretide 201201

    CATX(_,Year,Product)CATX(_,Year,Product,Code)

    2012_Seretide2012_Seretide_MAT

    Example:

    Code=MAT (no blanks)Product= Seretide (leading blanks)Year=2012 (trailing blanks)Yrmo= 201201 (leading and trailing blanks)

  • 5/21/2018 SAS Functions

    22/40

    GSK Knowledge Centre @ 2011

    Sample Program for Demonstrating the fourconcatenation functions

    Primary functions: CAT, CATS, CATT, CATX;

    DATA CAT_FUNCTIONS;

    STRING1 = "ABC"; * No spaces;

    STRING2 = "DEF "; * Three trailing spaces;

    STRING3 = " GHI"; * Three leading spaces;

    STRING4 = " JKL "; * Three leading and trailing spaces;

    LENGTH JOIN1 - JOIN5 $ 20;JOIN1 = CAT(STRING2, STRING3);

    JOIN2 = CATS(STRING2, STRING4);

    JOIN3 = CATT(STRING2, STRING1);

    JOIN4 = CATX(" ",STRING1,STRING3);

    JOIN5 = CATX(",",STRING3,STRING4);

    RUN;

    PROC PRINT DATA=CAT_FUNCTIONS NOOBS;

    TITLE "Listing of Data Set CAT_FUNCTIONS";

    RUN;

  • 5/21/2018 SAS Functions

    23/40

    GSK Knowledge Centre @ 2011

    Output

    String1 String2 String3 String4 Join1 Join2 Join3 Join4 Join5

    ABC DEF GHI JKL DEF GHI DEFJKL DEFABC ABCGHI

    GHI,JKL

  • 5/21/2018 SAS Functions

    24/40

    GSK Knowledge Centre @ 2011

    Character Functions

    Functions that divide strings into words"

    SCAN: Extracts a specified word from a character expression, whereword is defined as the characters separated by a set of specifieddelimiters. The length of the returned variable is 200, unlesspreviously defined.

    Syntax: SCAN(character-value, n-word )

    character-value is any SAS character expression.

    n-word is the nth "word" in the string. If n is greater than thenumber of words, the SCAN function returns a value that containsno characters. If n is negative, the character value is scanned fromright to left. A value of zero is invalid.

    C

  • 5/21/2018 SAS Functions

    25/40

    GSK Knowledge Centre @ 2011

    Character Functions

    Examples:STRING1 = "ABC DEF"

    STRING2 = "ONE?TWO THREE+FOUR|FIVE

    Syntax: Output:

    SCAN(STRING1,2) "DEF"

    SCAN(STRING1,-1) "DEF"

    SCAN(STRING1,3) no characters

    SCAN(STRING2,4) "FIVE"

    SCAN(STRING2,2," ") "THREE+FOUR|FIVE"SCAN(STRING1,0) An error in the SAS log

  • 5/21/2018 SAS Functions

    26/40

    GSK Knowledge Centre @ 2011

    Character Functions

    Functions that substitute letters or words in strings

    TRANSLATE: To exchange one character value for another.

    For example, you might want to change values 15 to the values AE.

    Syntax: TRANSLATE(character-value, to-1, from-1 )

    character-value is any SAS character expression.

    to-n is a single character or a list of character values.

    from-n is a single character or a list of characters. Each character listed in from-n is changed to the corresponding

    value in to-n. If a character value is not listed in from-n, it will beunaffected.

  • 5/21/2018 SAS Functions

    27/40

    GSK Knowledge Centre @ 2011

    Character Functions

    Example:CHAR = "12X45

    ANS = "Y

    Function Output

    TRANSLATE(CHAR,"ABCDE","12345") "ABXDE"

    TRANSLATE(CHAR,'A','1','B','2','C','3','D','4','E','5') "ABXDE"

    TRANSLATE(ANS,"10","YN") "1"

  • 5/21/2018 SAS Functions

    28/40

    GSK Knowledge Centre @ 2011

    Character Functions

    TRANWRD: To substitute one or more words in a string with areplacement word or words. It works like the find and replace featureof most word processors.

    Syntax: TRANWRD(character-value, from-string, to-string)

    character-value is any SAS character expression.

    from-string is one or more characters that you want to replace withthe character or characters in the to-string.

    to- string is one or more characters that replace the entire fromstring.

  • 5/21/2018 SAS Functions

    29/40

    GSK Knowledge Centre @ 2011

    Character Functions

    Examples:STRING = "123 Elm Road",

    FROM = "Road

    TO ="Rd.

    Function Output

    TRANWRD(STRING,FROM,TO) "123 Elm Rd."

    TRANWRD("Now is the time","is","is not") "Now is not the time"

    TRANWRD("one two three","four","4") "one two three"

    TRANWRD("Mr. Rogers","Mr."," ") " Rogers

  • 5/21/2018 SAS Functions

    30/40

    GSK Knowledge Centre @ 2011

    Character Functions

    Functions that compute the length of strings

    LENGTH: To determine the length of a character value, not countingtrailing blanks. A null argument returns a value of 1.

    Syntax: LENGTH(character-value)

    character-value is any SAS character expression.

    Examples

    CHAR = "ABC "

    Function OutputLENGTH("ABC") 3

    LENGTH(CHAR) 3

    LENGTH(" ") 1

  • 5/21/2018 SAS Functions

    31/40

    GSK Knowledge Centre @ 2011

    Character Functions

    Functions that count the number of letters or substrings in a string

    COUNT: To count the number of times a given substring appears in astring. With the use of a modifier, case can be ignored. If no occurrencesof the substring are found, the function returns a 0.

    Syntax: COUNT(character-value, find-string ) character-value is any SAS character expression.

    find-string is a character variable or SAS string literal to be counted.

    The following modifiers, placed in single or double quotation marks,may be used with COUNT:

    i or I ignore case.

    t or T ignore trailing blanks in both the character value and the

    find-string.

    Ch t F ti

  • 5/21/2018 SAS Functions

    32/40

    GSK Knowledge Centre @ 2011

    Character Functions

    Examples:STRING1 = "How Now Brown COW

    STRING2 = "ow

    Function Output

    COUNT(STRING1, STRING2) 3

    COUNT(STRING1,STRING2,'I') 4

    COUNT(STRING1, "XX") 0

    COUNT("ding and dong","g ") 1

    COUNT("ding and dong","g ","T") 2

  • 5/21/2018 SAS Functions

    33/40

    GSK Knowledge Centre @ 2011

    Character Functions

    COUNTC: To count the number of individual characters that appear ordo not appear ina string. With the use of a modifier, case can beignored. Another modifier allows you to count characters that do notappear in the string. If no specified characters are found, the functionreturns a 0.

    Syntax: COUNTC(character-value, characters )

    character-value is any SAS character expression.

    characters is one or more characters to be counted. It may be astring

    literal (letters in quotation marks) or a character variable. The following modifiers, placed in quotation marks, may be used with

    COUNTC:

    i or I ignore case.

  • 5/21/2018 SAS Functions

    34/40

    GSK Knowledge Centre @ 2011

    Character Functions

    o or O If this modifier is used, COUNTC processes the characteror characters and modifiers only once. If the COUNTC function isused in the same DATA step, the previous character and modifiervalues are used and the current values are ignored.

    t or T ignore trailing blanks in the character-value or the

    characters. Note, this modifier is especially important when

    looking for blanks or when you are using the v modifier (below).

    v or V count only the characters that do not appear in thecharacter-value. Remember that this count will include trailing

    blanks unless the t modifier is used.

  • 5/21/2018 SAS Functions

    35/40

    GSK Knowledge Centre @ 2011

    Character Functions

    Examples:

    STRING1 = "How Now Brown COW

    STRING2 = "wo

    Function Output

    COUNTC("AaBbbCDE","CBA") 3

    COUNTC("AaBbbCDE","CBA",'I') 7

    COUNTC(STRING1, STRING2) 6

    COUNTC(STRING1,STRING2,'I') 8

    COUNTC(STRING1, "XX") 0COUNTC("ding and dong","g ") 4 (2 g's and 2 blanks)

    COUNTC("ding and dong","g ","T") 2 (blanks trimmed)

    COUNTC("ABCDEabcde","BCD",'VI') 4 (A, E, a, and e)

  • 5/21/2018 SAS Functions

    36/40

    GSK Knowledge Centre @ 2011

    Date Functions

    Function Name Description Syntax &

    Example

    Output

    Date returns the currentdate as a SASdate value

    Var=Date(); Var=19004In order to displayin the date formatwe need to apply

    format date9. toget 12JAN2012

    Datejul converts a Juliandate to a SAS

    date value.A Julian date inSAS is a date inthe form yyddd oryyyyddd,

    DATEJUL(julian-date)

    Xstart=datejul(2011365);

    18992When you apply

    date format youwill get31DEC2011

  • 5/21/2018 SAS Functions

    37/40

    GSK Knowledge Centre @ 2011

    Date Functions

    Function

    Name

    Description Syntax & Example Output

    Datepart extracts the date from aSAS datetime value

    Datepart(datetime);End_dat=01Jan2100:00:00:00X=datepart(end_dat)

    X=01Jan2100

    DATETIME returns the current dateand time of day X=Datetime(); X=1641999488.3

    Day returns the day of themonth from a SAS datevalue

    Syn :-day(date);X=day(date());

    X=12

    Month returns the month froma SAS date value

    Syn :-Month(date);X=month(date());

    X=01

    Year returns the year from aSAS date value

    Syn :-Year(date);X=year(01JAN2012);

    X=2012

  • 5/21/2018 SAS Functions

    38/40

    GSK Knowledge Centre @ 2011

    Date Functions

    Function

    Name

    Description Syntax & Example Output

    MDY Returns a SAS date valuefrom month, day, andyear values

    Syn:MDY(month,day,year)a=MDY(9,3,2012);y=DAY(a);

    A=09/03/2012Y=3

    QTR Returns the yearly quarter

    (1-4) from a SAS datevalue

    Syn:QTR(date)

    Date=QTR (09/03/2012);

    Date=3

    To get in date we need toapply date format.

    Today() returns the current date asa SAS date value

    Syn : today();X=today();

    19012After applying date formatx=20Jan2012

    Weekday() returns the day of the weekfrom a SAS date value.

    Syn: Weekday(date);X=weekday(today())

    X=6 ( means Friday)

  • 5/21/2018 SAS Functions

    39/40

    GSK Knowledge Centre @ 2011

    Date Functions

    INTCK: To determine the number of time periods which have beencrossed between two SAS date, time or datetime variables.

    Syntax: INTCK(interval,from,to)

    Where: interval = character constant or variable name

    representing the time period of interest enclosed in single quotes

    from = SAS date, time or datetime value identifying the start of atime span

    to = SAS date, time or datetime value identifying the end of a timespan

    Example Output

    Date1=01JAN1980d

    Date2=01JAN2012d

    X=intck(year,date1,date2); x=32

  • 5/21/2018 SAS Functions

    40/40

    Date Functions

    INTNX: Creates a SAS date, time or datetime value that is a givennumber of time intervals from a starting value.

    Syntax:INTNX(interval,from,to)

    Where interval, from and to have the same meanings and definitionsas for the INTCK function described earlier.

    Example: Output

    date=01Jan2012d

    X=intnx(month,date,5); x=19145After applying Date format date9. we will get01Jun2012