Complete Sas

download Complete Sas

of 284

Transcript of Complete Sas

  • 8/6/2019 Complete Sas

    1/284

    SAS Training 1

    What is SAS?

    Statistical Analysis Softwaredeveloped by SAS Institute in Cary, NC

    Main Uses of SAS data entry, retrieval, and management report writing and graphics statistical and mathematical analysis business planning, forecasting, and decision support operations research and project management quality improvement applications development.

  • 8/6/2019 Complete Sas

    2/284

    SAS Training 2

    Basics about SAS

    SAS is composed of three windows

    Program Editor

    where you write and submit programs

    Log

    where SAS displays messages which indicates anyerrors that may be in a program

    OutputWhere result appear after submitting programs

  • 8/6/2019 Complete Sas

    3/284

    SAS Training 3

    Program Editor Window

    Write your codein this window

    Explorer andResultsWindow

  • 8/6/2019 Complete Sas

    4/284

    SAS Training 4

    Log Window

    Log Window

    View the Log Created by

    the Program Execution

  • 8/6/2019 Complete Sas

    5/284

    SAS Training 5

    Output Window

    Output Window

    View the Values of aDataset in this Window

  • 8/6/2019 Complete Sas

    6/284

  • 8/6/2019 Complete Sas

    7/284SAS Training 7

    Example of a SAS Data set

    53 Lucy 42 41

    54 Tom 46 54

    55 Dan 43 .

    56 Tim 45 56

    57 42 48

    58 Mary 48 43

    ID NAME

    HT WT

    12

    3

    4

    5

    6

    Observations

    Variables

    ID, HT and WT are Numeric Variables

    NAME is a Character Variable

    Character Variables if blank are represented by a space

    Numeric Variables if blank are represented by a .

  • 8/6/2019 Complete Sas

    8/284SAS Training 8

    Building Blocks of a SAS Program

    A SAS program is constructed from two buildingblocks

    1) DATA Step

    2) PROC Step

    A typical SAS program starts with a DATA step to

    create a SAS dataset and then passes on to thePROC step to do the analysis.

  • 8/6/2019 Complete Sas

    9/284SAS Training 9

    Basic Components of SAS, Continued

    Data Step

    SAS statement that read data, create new datasets or

    variables, modify datasets, perform calculation.

    Procedures

    SAS statements that can perform statisticalanalyses, create & print reports & graphs

  • 8/6/2019 Complete Sas

    10/284SAS Training 10

    PROC Step

    Basic Components of SAS Every SAS program is constructed using the Data Step and/or

    Procedures

    e.g. DATA distance;

    miles = 23;

    kilometer = 1.61 * miles;

    RUN;

    PROC PRINT DATA = distance;

    RUN;

    Any combination of Data Step and/or Procedures may be used

    Run statement should be used throughout the program

    DATA Step

  • 8/6/2019 Complete Sas

    11/284SAS Training 11

    Difference Between a DATA step and

    a PROC step

    DATA steps PROC

    steps Begin with DATA statements Begin with PROC

    statements

    Read and modify data Perform specific analysis orfunction

    Create a SAS data set Produce results or reportNote: The table is not meant to imply that PROC can never createSAS data sets (some do), or that DATA step can never createreports (they can)

    But it is much easier to write SAS programs if one can understand

    the basic functions of DATA and PROC steps.

  • 8/6/2019 Complete Sas

    12/284SAS Training 12

    Execution of SAS data set Data Steps execute line by line and observation by

    observation SAS takes the first observation and runs it all the way

    through the data step (line by line) before looping backto pick up the second observation

    SAS sees one observation at a time.

    Input data set

    Observation 1

    Observation 2

    Observation 3

    DATA step

    Line 1

    Line 2

    Line 3

    Line 4

    Line 5

    Output dataset

    Observation 2

    Observation 3

    Observation 1

  • 8/6/2019 Complete Sas

    13/284

    SAS Training 13

    Rules for SAS programs

    Every SAS statement end with a semicolon.

    e.g. Data test;

    Names must be 8 characters or fewer in length.e.g. valid names:- distance invalid names is distance_a

    Names must be start with letter or an underscore (_).

    Valid Names are

    e.g. distance, _abc are valid.

    Names can contain only letters, numerals and the underscore(_).

    No %$!*@ please.

  • 8/6/2019 Complete Sas

    14/284

    SAS Training 14

    Rules for SAS program

    StatementsSAS program statements can Be in upper or lower case

    Continue on the next line Be on the same line as other statements Start in any column

  • 8/6/2019 Complete Sas

    15/284

    SAS Training 15

    READING DATA FROM

    EXTERNAL FILESSAS can read data and create adata set from external files like txt,

    csv, etc.Basic Code Structure

    DATA dataset-name;

    INFILEfile-specification ;INPUT ;

    Run;

  • 8/6/2019 Complete Sas

    16/284

    SAS Training 16

    Reading data using

    DATALINESA SAS data set can also be created bytyping values

    in the SAS program editor using DATALINES;

    Basic Code Structure

    DATA dataset-name;INPUT ;DATALINES;..

    ..;Run;

  • 8/6/2019 Complete Sas

    17/284

    SAS Training 17

    INPUT

    Describes the arrangement ofvalues in the input data recordand assigns input values to thecorresponding SAS variables

    INPUT ;

  • 8/6/2019 Complete Sas

    18/284

    SAS Training 18

    INPUT (SPECIFICATIONS)variable - names a variable that is assigned input values

    $ - indicates to store the variable value as a character valuerather than as a numeric value.

    pointer-control - moves the input pointer to a specified line orcolumn in the input buffer.

    informat. - specifies an informat to use to read the variablevalue

  • 8/6/2019 Complete Sas

    19/284

    SAS Training 19

    EXAMPLE 1 (EXTERNAL

    FILE)

    Data newdata;

    Infile C:/dat.txt;

    Input name $ age;

    Run;

    Mary 24Suzan 34Dat.txt in C:/

    Resulting SAS data set(newdata)

  • 8/6/2019 Complete Sas

    20/284

    SAS Training 20

    INPUT (DATALINES)Data newdata;

    Input name $ age;

    DATALINES;Mary 24

    Suzan 32

    ;Run;

  • 8/6/2019 Complete Sas

    21/284

    SAS Training 21

    INPUT TYPESINPUT, COLUMN : Reads input values

    from specified columns and assigns

    them to the corresponding SAS variables

    Syntax:

    INPUT variable start-column ;

  • 8/6/2019 Complete Sas

    22/284

    SAS Training 22

    Exampledata scores;

    input name $ 1-18 score1 25-27 score2 30-32 score3 35-

    37;datalines;

    Joseph 11 32 76

    Mitchel 13 29 82

    Sue Ellen 14 27 74

    ;

    Run;

  • 8/6/2019 Complete Sas

    23/284

    SAS Training 23

    INPUT TYPESINPUT, Formatted : Reads input values with

    specified informats and assigns them to thecorresponding SAS variables.

    Syntax:

    INPUT variable informat.

    ;

  • 8/6/2019 Complete Sas

    24/284

    SAS Training 24

    Exampledata sales;

    infile file-specification;

    input item $10. +5 jan comma5. +5 feb comma5. +5

    mar comma5.;run;

    It can read these input data records:

    ----+----1----+----2----+----3----+----4

    trucks 1,382 2,789 3,556

    vans 1,265 2,543 3,987

    sedans 2,391 3,011 3,658

  • 8/6/2019 Complete Sas

    25/284

    SAS Training 25

    INPUT TYPESINPUT, List : Scans the input data record for

    input values and assigns them to thecorresponding SAS variables.

    Syntax :

    INPUT variable ;

  • 8/6/2019 Complete Sas

    26/284

    SAS Training 26

    Exampledata scores;

    input name $ score1 score2 score3 team $;

    datalines;Joe 11 32 76 red

    Mitchel 13 29 82 blue

    Susan 14 27 74 green;

  • 8/6/2019 Complete Sas

    27/284

    SAS Training 27

    Merge StatementThe MERGE statement is flexible

    and has a variety of uses in SAS

    programming One-to-One Match Merge

  • 8/6/2019 Complete Sas

    28/284

    SAS Training 28

    One-to-one matchingTo combine variables from several

    data sets where there is a one-to-

    one correspondence between theobservations in each of the datasets, list the data sets to be joined

    on a merge statement.

  • 8/6/2019 Complete Sas

    29/284

    SAS Training 29

    Match Merge When there is not an exact one-to-one

    correspondence between data sets to be

    merged, the variables to use to identifymatching observations can be specied on aby statement.

    The data sets being merged must be sorted

    by the variables specified on the bystatement.

  • 8/6/2019 Complete Sas

    30/284

    SAS Training 30

    Example One to One

    Merge

  • 8/6/2019 Complete Sas

    31/284

    SAS Training 31

    Example Match Merge

  • 8/6/2019 Complete Sas

    32/284

    SAS Training 32

    Example Match Merge

  • 8/6/2019 Complete Sas

    33/284

    SAS Training 33

    Manipulating result of merge statement

    with IN values

    * IN option indicates which data set recordcame from;

    DATA new;MERGE old1 (IN=INOLD1) old2 (IN=IN0LD2);

    BY NAME

    IF INOLD1 and INOLD2;RUN;

    * If statement keeps only those recordsthat are in both data sets;

  • 8/6/2019 Complete Sas

    34/284

    SAS Training 34

    SAS Functions Definition of Functions

    A SAS function performs a computation or systemmanipulation on arguments and returns a value. Most functionsuse arguments supplied by the user, but a few obtain theirarguments from the operating environment.

    In base SAS software, you can use SAS functions in DATA stepprogramming statements, in a WHERE expression, in macro

    language statements, in PROC REPORT, and in StructuredQuery Language (SQL).

  • 8/6/2019 Complete Sas

    35/284

    SAS Training 35

    Syntax of Functions The syntax of a function is

    function-name (argument-1)

    function-name (OF variable-list)

    wherefunction-name

    names the function.

    argument

    can be a variable name, constant, or any SAS expression, includinganother function. The number and kind of arguments allowed are

    described with individual functions. Multiple arguments are

    separated by a comma.

  • 8/6/2019 Complete Sas

    36/284

    SAS Training 36

    Selected SAS Functions Numeric Functions

    ROUND : Rounds to the nearest round-off unit.

    Syntax

    ROUND(argument,round-off-unit)

    Arguments

    argument

    is numeric.

    round-off-unit

    is numeric and nonnegative.

    Details :The ROUND function returns a value rounded to the nearest round-off unit.Ifround-off-unitis not provided, a default value of 1 is used and argumentisrounded to the nearest integer.

  • 8/6/2019 Complete Sas

    37/284

    SAS Training 37

    Selected SAS FunctionsFunction ROUND Examples :

    SAS Statement Results

    var1=223.456;x=round(var1,1); put x 9.5; 223.00000

    var2=223.456;x=round(var2,.01); put x9.5;

    223.46000

    x=round(223.456,100); putx 9.5;

    200.00000

    x=round(223.456); put x9.5;

    223.00000

    x=round(223.456,.3); put x9.5;

    223.33333

  • 8/6/2019 Complete Sas

    38/284

    SAS Training 38

    Selected SAS Functions SUM : Returns the sum of the nonmissing

    arguments.

    Syntax

    SUM(argument,argument, ...)

    Arguments

    argument

    is numeric. The argument list can consist of a variablelist, which is preceded by OF.

  • 8/6/2019 Complete Sas

    39/284

  • 8/6/2019 Complete Sas

    40/284

    SAS Training 40

    Selected SAS Functions MEAN : Returns the arithmetic mean (average)

    Syntax

    MEAN(argument,argument, . . .)

    Arguments argument

    is numeric. At least one argument is required. Theargument list may consist of a variable list, which ispreceded by OF.

    Examples : SAS Statement Results

    x1=mean(2,.,.,6); 4

    x2=mean(1,2,3,2); 2

    x3=mean(of x1-x2); 3

  • 8/6/2019 Complete Sas

    41/284

    SAS Training 41

    Selected SAS Functions INT : Returns the integer value.

    Syntax

    INT(argument)

    Arguments

    argument

    is numeric.

    Details

    The INT function returns the integer portion of the argument (truncatesthe decimal portion). If the value of argument is positive, INT(argument)

    has the same result as FLOOR(argument). If the value of argument isnegative, INT(argument) has the same result as CEIL(argument).

  • 8/6/2019 Complete Sas

    42/284

    SAS Training 42

    Selected SAS FunctionsFunction INT Examples :

    SAS Statement Results

    var1=2.1;

    x=int(var1);

    put x=;

    2

    var2=-2.4;

    y=int(var2);

    put y=;

    -2

    a=int(3);

    put a=;

    3

    b=int(-1.6);

    put b=;

    -1

  • 8/6/2019 Complete Sas

    43/284

    SAS Training 43

    Selected SAS Functions LAG : Returns values from a queue.

    Syntax

    LAG(argument)

    Argumentsn

    specifies the number of lagged values.

    argument

    is numeric or character.

    Details

    The LAG functions, LAG1, LAG2, . . . , LAG100 return values from a queue. LAG1

    can also be written as LAG. A LAGn function stores a value in a queue and returnsa value stored previously in that queue.

  • 8/6/2019 Complete Sas

    44/284

    SAS Training 44

    Selected SAS FunctionsFunction LAG Examples : Creating a Data Set

    The following program creates a data set that contains the values for X, Y, andZ.

    options pagesize=25 linesize=64 nodate pageno=1;

    data one;

    input X @@;

    Y=lag1(x);

    Z=lag2(x);

    datalines;

    1 2 3 4 5 6 ;

    proc print;

    title 'Lag Output';

    run;

  • 8/6/2019 Complete Sas

    45/284

    SAS Training 45

    Selected SAS FunctionsFunction LAG Examples : Creating a Data Set :LAG1 returns one missing value and the

    values of X (lagged once). LAG2 returns two missing values and thevalues of X (lagged twice).

    Lag Output 1

    Obs X Y Z

    1 1 . .2 2 1 .3 3 2 14 4 3 25 5 4 36 6 5 4

  • 8/6/2019 Complete Sas

    46/284

    SAS Training 46

    Selected SAS Functions Character Functions

    UPCASE: Converts all letters in an argument to uppercase.

    Syntax

    UPCASE(argument)

    Arguments

    argument

    specifies any SAS character expression.

    Details :

    The UPCASE function copies a character argument, converts all lowercase lettersto uppercase letters, and returns the altered value as a result.

  • 8/6/2019 Complete Sas

    47/284

    SAS Training 47

    Selected SAS FunctionsFunction UPCASE Examples :

    SAS Statement Results

    name=upcase('John B.Smith'); put name;

    JOHN B. SMITH

  • 8/6/2019 Complete Sas

    48/284

    SAS Training 48

    Selected SAS Functions LOWCASE: Converts all letters in an argument to lowercase.

    Syntax

    LOWCASE(argument)

    Arguments

    argumentspecifies any SAS character expression.

    Details :

    The LOWCASE function copies a character argument, converts all uppercaseletters to lowercase letters, and returns the altered value as a result.

  • 8/6/2019 Complete Sas

    49/284

    SAS Training 49

    Selected SAS FunctionsFunction LOWCASE Examples :

    SAS Statement Results

    x='INTRODUCTION';y=lowcase(x);

    put y;

    introduction

  • 8/6/2019 Complete Sas

    50/284

    SAS Training 50

    Selected SAS Functions SUBSTR (left of=): Replaces character value contents

    Syntax

    SUBSTR(argument,position)=characters-to-replace

    Arguments

    argument

    specifies a character variable. position

    specifies a numeric expression that is the beginning character position.

    n

    specifies a numeric expression that is the length of the substring that will bereplaced.

    characters-to-replace

    specifies a character expression that will replace the contents of argument.

  • 8/6/2019 Complete Sas

    51/284

    SAS Training 51

    Selected SAS FunctionsDetails

    When you use the SUBSTR function on the left side of anassignment statement, SAS places the value ofargumentwith theexpression on right side. SUBSTR replaces n characters starting at

    the character you specify inposition.

    Function SUBSTR(left of =) Examples :

    SAS Statement Results

    a='KIDNAP';

    substr(a,1,3)='CAT';put a;

    CATNAP

    b=a;

    substr(b,4)='TY';

    put b;

    CATTY

  • 8/6/2019 Complete Sas

    52/284

    SAS Training 52

    Selected SAS Functions SUBSTR(right of=):Extracts a substring from an argument

    Syntax

    SUBSTR(argument,position)

    Arguments

    variable

    specifies a valid SAS variable name. argument

    specifies any SAS character expression.

    position

    specifies a numeric expression that is the beginning character position.

    n

    specifies a numeric expression that is the length of the substring to extract.

  • 8/6/2019 Complete Sas

    53/284

    SAS Training 53

    Selected SAS FunctionsDetails

    The SUBSTR function returns a portion of an expression that youspecify in argument. The portion begins with the character specifiedbyposition and is the number of characters specified by n.

    A variable that is created by SUBSTR obtains its length from thelength ofargument.

    Function SUBSTR(right of =) Examples :

    SAS Statement Results

    ----+----1----+----2

    date='06MAY98';month=substr(date,3,3);year=substr(date,6,2);

    put @1 month @5 year;

    MAY 98

  • 8/6/2019 Complete Sas

    54/284

    SAS Training 54

    Selected SAS Functions SCAN : Selects a given word from a character expression.

    Syntax

    SCAN(argument,n)

    Arguments

    argument

    specifies any character expression. n

    specifies a numeric expression that produces the number of the word in thecharacter string you want SCAN to select.

    delimiters

    specifies a character expression that produces characters that you want SCAN to useas word separators in the character string.

  • 8/6/2019 Complete Sas

    55/284

    SAS Training 55

    Selected SAS FunctionsDetails

    Leading delimiters before the first word in the character string donot effect SCAN. If there are two or more contiguous delimiters,SCAN treats them as one.

    Function SCAN Examples :

    SAS Statement Results

    arg='ABC.DEF(X=Y)';

    word=scan(arg,3);put word;

    X=Y

    word=scan(arg,-3);

    put word;

    ABC

  • 8/6/2019 Complete Sas

    56/284

    SAS Training 56

    Selected SAS Functions TRIM: Removes trailing blanks from character expressions and

    returns one blank if the expression is missing.

    Syntax

    TRIM(argument)

    Arguments

    argumentspecifies any SAS character expression.

    Details :

    TRIM copies a character argument, removes all trailing blanks, and returns thetrimmed argument as a result. If the argument is blank, TRIM returns one blank.

    TRIM is useful for concatenating because concatenation does not remove trailingblanks.

    Assigning the results of TRIM to a variable does not affect the length of the receiving

    variable. If the trimmed value is shorter than the length of the receiving variable,SAS pads the value with new blanks as it assigns it to the variable.

  • 8/6/2019 Complete Sas

    57/284

    SAS Training 57

    Selected SAS FunctionsFunction TRIM Examples :

    1. Removing Trailing Blanks

    These statements and this data line produce these results:

    data test;

    input part1 $ 1-10 part2 $ 11-20;

    hasblank=part1||part2;

    noblank=trim(part1)||part2;

    put hasblank;

    put noblank;

    datalines; Data Line Resultsapple sauce ----+----1----+----2

    apple sauce

    applesauce

  • 8/6/2019 Complete Sas

    58/284

    SAS Training 58

    Selected SAS Functions TRANSLATES : Replaces specific characters in a character expression.

    Syntax

    TRANSLATE(source,to-1,from-1)

    Arguments

    source

    specifies the SAS expression that contains the original character value.

    tospecifies the characters that you want TRANSLATE to use as substitutes.

    from

    specifies the characters that you want TRANSLATE to replace.

  • 8/6/2019 Complete Sas

    59/284

    SAS Training 59

    Selected SAS FunctionsDetails

    The maximum number of pairs ofto and from arguments thatTRANSLATE accepts depends on the operating environment you useto run SAS. There is no functional difference between using several

    pairs of short arguments, or fewer pairs of longer arguments.

    Function TRANSLATE Examples :

    SAS Statement Results

    x=translate('XYZW','AB','VW');

    put x;

    XYZB

  • 8/6/2019 Complete Sas

    60/284

    SAS Training 60

    Selected SAS Functions LENGTH: Returns the length of an argument.

    Syntax LENGTH(argument)

    Arguments

    argument

    specifies any SAS expression.

    Details :

    The LENGTH function returns an integer that represents the position of the right-most nonblank character in the argument. If the value of the argument is missing,LENGTH returns a value of 1. If the argument is a numeric variable (either initializedor uninitialized), LENGTH returns a value of 12 and prints a note in the SAS log thatthe numeric values have been converted to character values.

  • 8/6/2019 Complete Sas

    61/284

    SAS Training 61

    Selected SAS FunctionsFunction LENGTH Examples :

    SAS Statements Results

    len=length('ABCDEF');

    put len;

    6

  • 8/6/2019 Complete Sas

    62/284

    SAS Training 62

    Selected SAS Functions INDEX: Searches a character expression for a string of characters. Syntax INDEX(source,excerpt)

    Arguments

    source

    specifies the character expression to search.

    excerpt

    specifies the string of characters to search for in the character expression.

    Details :

    The INDEX function searches source, from left to right, for the first occurrence of the stringspecified in excerpt, and returns the position in source of the string's first character. If thestring is not found in source, INDEX returns a value of 0. If there are multiple occurrencesof the string, INDEX returns only the position of the first occurrence.

  • 8/6/2019 Complete Sas

    63/284

    SAS Training 63

    Selected SAS FunctionsFunction INDEX Examples :

    SAS Statements Results

    a='ABC.DEF (X=Y)';

    b='X=Y';x=index(a,b);

    put x;

    10

  • 8/6/2019 Complete Sas

    64/284

    SAS Training 64

    SAS Statements Definition of Statements

    A SAS statement is a series of items that may include keywords, SAS names, special characters, andoperators. All SAS statements end with a semicolon. A SAS statement either requests SAS to perform anoperation or gives information to the system.

    There are two kinds of SAS statements:

    those used in DATA step programming

    those that are global in scope and can be used anywhere in a SAS program.

  • 8/6/2019 Complete Sas

    65/284

    SAS Training 65

    Selected SAS Statements DATA stepStatements

    DELETE : Stops processing the current observation.

    Syntax

    DELETE;Without Arguments

    When DELETE executes, the current observation is not written to a data set,and SAS returns immediately to the beginning of the DATA step for the nextiteration.

    Details :The DELETE statement is often used in a THEN clause of an IF-

    THEN statement or as part of a conditionally executed DO group.

  • 8/6/2019 Complete Sas

    66/284

    SAS Training 66

    Selected SAS StatementsStatement DELETE Examples :

    Example 1: Using the DELETE Statement as Part of an IF-THENStatement

    When the value of LEAFWT is missing, the current observation is deleted:

    if leafwt=. then delete;

    Example 2: Using the DELETE Statement to Subset Raw Data

    data topsales;

    infile file-specification;

    input region office product yrsales;

    if yrsales

  • 8/6/2019 Complete Sas

    67/284

  • 8/6/2019 Complete Sas

    68/284

    SAS Training 68

    Selected SAS StatementsStatement DO Examples :

    In this simple DO group, the statements between DO and END areperformed only when YEARS is greater than 5. If YEARS is less than

    or equal to 5, statements in the DO group do not execute, and theprogram continues with the assignment statement that follows theELSE statement.

    if years>5 then

    do;

    months=years*12;

    put years= months=;end;

    else yrsleft=5-years;

  • 8/6/2019 Complete Sas

    69/284

    SAS Training 69

    Selected SAS Statements DROP : Excludes variables from output SAS data sets Syntax DROP variable-list;

    Arguments

    variable-list

    specifies the names of the variables to omit from the output data set.

    Details :The DROP statement applies to all the SAS data sets that are created withinthe same DATA step and can appear anywhere in the step. The variables in the DROPstatement are available for processing in the DATA step. If no DROP or KEEP statementappears, all data sets that are created in the DATA step contain all variables. Do notuse both DROP and KEEP statements within the same DATA step.

  • 8/6/2019 Complete Sas

    70/284

    SAS Training 70

    Selected SAS StatementsStatement DROP Examples :

    These examples show the correct syntax for listing variables with the DROPstatement:

    drop time shift batchnum;

    drop grade1-grade20; In this example, the variables PURCHASE and REPAIR are used in processingbut are not written to the output data set INVENTRY:

    data inventry;

    drop purchase repair;

    infile file-specification;

    input unit part purchase repair;

    totcost=sum(purchase,repair);

    run;

  • 8/6/2019 Complete Sas

    71/284

    SAS Training 71

    Selected SAS Statements KEEP : Includes variables in output SAS data sets

    Syntax

    KEEPvariable-list;

    Arguments

    variable-list

    specifies the names of the variables to write to the output data set.

    Details :The KEEP statement causes a DATA step to write only the variables that you specifyto one or more SAS data sets. The KEEP statement applies to all SAS data sets that arecreated within the same DATA step and can appear anywhere in the step. If no KEEP or DROPstatement appears, all data sets that are created in the DATA step contain all variables.

  • 8/6/2019 Complete Sas

    72/284

  • 8/6/2019 Complete Sas

    73/284

    SAS Training 73

    Selected SAS Statements LABEL : Assigns descriptive labels to variables

    Syntax

    LABELvariable-1='label-1' . . . ;

    LABELvariable-1=' ' . . . ;

    Arguments

    variablenames the variable that you want to label

    'label'

    specifies a label of up to 256 characters, including blanks.

    ' '

    removes a label from a variable. Enclose a single blank space in quotation marks toremove an existing label.

  • 8/6/2019 Complete Sas

    74/284

    SAS Training 74

    Selected SAS StatementsDetails

    Using a LABEL statement in a DATA step permanently associates labels with variablesby affecting the descriptor information of the SAS data set that contains the variables.You can associate any number of variables with labels in a single LABEL statement.

    Statement LABEL Examples :

    Specifying Labels

    Here are several LABEL statements: label compound='Type of Drug'; label date="Today's Date "; label n='Mark''s Experiment Number'; label score1="Grade on April 1 Test" score2="Grade on May 1 Test";

  • 8/6/2019 Complete Sas

    75/284

  • 8/6/2019 Complete Sas

    76/284

    SAS Training 76

    Selected SAS Statements LENGTH : Specifies the number of bytes for storing variables

    Syntax

    LENGTH variable-specification(s) ;

    Arguments

    variable-specification

    is a required argument and has the form where

    variablenames one or more variables that are to be assigned a length. This includes any variables in

    the DATA step, including those dropped from the output data set.

    $

    indicates that the preceding variables are character variables.

    length

    specifies a numeric constant that is the number of bytes used for storing variable values.

  • 8/6/2019 Complete Sas

    77/284

    SAS Training 77

    Selected SAS StatementsDEFAULT=n

    changes the default number of bytes that SAS uses to storethe values of any newly created numeric variables.

    Details

    In general, the length of a variable depends on whether the variable is numeric or character how the variable was created whether a LENGTH statement is present.

  • 8/6/2019 Complete Sas

    78/284

  • 8/6/2019 Complete Sas

    79/284

    SAS Training 79

    Selected SAS StatementsStatement RENAME Examples :

    These examples show the correct syntax for renaming variables using the RENAME statement

    rename street=address;

    rename time1=temp1 time2=temp2 time3=temp3;

    rename name=Firstname

    score1-score3=Newscore1-Newscore3; This example uses the old name of the variable in program statements. The variable Olddept is

    named Newdept in the output data set, and the variable Oldaccount is named Newaccount.

    rename Olddept=Newdept Oldaccount=Newaccount;

    if Oldaccount>5000;

    keep Olddept Oldaccount items volume;

  • 8/6/2019 Complete Sas

    80/284

    SAS Training 80

    Selected SAS Statements WHERE : Selects observations from SAS data sets that meet a particular condition

    Syntax

    WHEREwhere-expression-1< logical-operatorwhere-expression-n>;

    Arguments

    where-expression

    is an arithmetic or logical expression that generally consists of a sequence of operands and operators.

    logical-operatorcan be AND, AND NOT, OR, or OR NOT.

    Details :Using the WHERE statement may improve the efficiency of your SAS programs because SAS is notrequired to read all observations from the input data set.

    The WHERE statement cannot be executed conditionally; that is, you cannot use it as part of an IF-THENstatement.

    WHERE statements can contain multiple WHERE expressions that are joined by logical operators.

  • 8/6/2019 Complete Sas

    81/284

    SAS Training 81

    Selected SAS StatementsStatement WHERE Examples :

    Basic WHERE Statement Usage

    This DATA step produces a SAS data set that contains only observations from data set CUSTOMER in which thevalue for NAME begins with Mac and the value for CITY is Charleston or Atlanta

    data testmacs;

    set customer;

    where substr(name,1,3)='Mac' and

    (city='Charleston' or city='Atlanta');run;

    Using Operators Available Only in the WHERE Statement

    Using BETWEEN-AND:

    where empnum between 500 and 1000;

    Using CONTAINS:

    where company ? 'bay';

    where company contains 'bay';

  • 8/6/2019 Complete Sas

    82/284

    SAS Training 82

    Selected SAS Statements IF-THEN/ELSE : Executes a SAS statement for observations that meet specific

    conditionsSyntax

    IFexpressionTHENstatement;

    Arguments

    expressionis any SAS expression and is a required argument.

    statement

    can be any executable SAS statement or DO group.

  • 8/6/2019 Complete Sas

    83/284

  • 8/6/2019 Complete Sas

    84/284

    SAS Training 84

    Selected SAS StatementsStatement IF-THEN\ELSE Examples :

    These examples show different ways of specifying the IF-THEN/ELSE statement if x then delete;

    if status='OK' and type=3 then count+1;

    if age ne agecheck then delete;

    if x=0 then

    if y ne 0 then put 'X ZERO, Y NONZERO';

    else put 'X ZERO, Y ZERO';

    else put 'X NONZERO';

  • 8/6/2019 Complete Sas

    85/284

    SAS Training 85

    Selected SAS Statements BY: Controls the operation of a SET, MERGE, MODIFY, or UPDATE statement in the

    DATA step and sets up special grouping variables

    Syntax

    BY variable-1 ;

    Arguments

    DESCENDING

    indicates that the data sets are sorted in descending order by the variable that is specified. DESCENDINGmeans largest to smallest numerically, or reverse alphabetical for character variables.

  • 8/6/2019 Complete Sas

    86/284

    SAS Training 86

    Selected SAS Statementsvariable

    names each variable by which the data set is sorted or indexed. These variables are referred toas BY variables for the current DATA or PROC step.

    NOTSORTED

    specifies that observations with the same BY value are grouped together but are not necessarilysorted in alphabetical or numeric order.

    Details :In a DATA Step the BY statement applies only to the SET, MERGE, MODIFY, or UPDATEstatement that precedes it in the DATA step, and only one BY statement can accompany each ofthese statements in a DATA step

    In PROC step you can specify the BY statement with some SAS procedures to modify their action.

  • 8/6/2019 Complete Sas

    87/284

    SAS Training 87

    Selected SAS StatementsStatement BY Examples :

    Specifying One or More BY Variables

    Observations are in ascending order of the variable DEPT:

    by dept;

    Specifying Sort Order

    Observations are in ascending order of SALESREP and, within eachSALESREP value, in descending order of the values of JANSALES:

    by salesrep descending jansales; BY-Processing with Nonsorted Data

    Observations are ordered by the name of the month in which theexpenses were accrued:

    by month notsorted;

  • 8/6/2019 Complete Sas

    88/284

    SAS Training 88

    Selected SAS Statements RETAIN : Causes a variable that is created by an INPUT or assignment statement to

    retain its value from one iteration of the DATA step to the nextSyntax

    RETAIN >;

    Without Arguments

    If you do not specify an argument, the RETAIN statement causes the values of all variables that arecreated with INPUT or assignment statements to be retained from one iteration of the DATA step tothe next.

  • 8/6/2019 Complete Sas

    89/284

    SAS Training 89

    Selected SAS StatementsArguments

    element-list

    specifies variable names, variable lists, or array names whose values you want retained.

    initial-value

    specifies an initial value, numeric or character, for one or more of the preceding elements.

    (initial-value-list)

    specifies an initial value, numeric or character, for individual elements in the preceding list. SAS

    matches the first value in the list with the first variable in the list of elements, the second value withthe second variable, and so on.

  • 8/6/2019 Complete Sas

    90/284

    SAS Training 90

    Selected SAS StatementsDetails:

    Without a RETAIN statement, SAS automatically sets variables that are assigned values by anINPUT or assignment statement to missing before each iteration of the DATA step.

    Use a RETAIN statement to specify initial values for individual variables, a list of variables, ormembers of an array. If a value appears in a RETAIN statement, variables that appear before itin the list are set to that value initially. (If you assign different initial values to the samevariable by naming it more than once in a RETAIN statement, SAS uses the last value.) You can

    also use RETAIN to assign an initial value other than the default value of 0 to a variable whosevalue is assigned by a sum statement.

  • 8/6/2019 Complete Sas

    91/284

    SAS Training 91

    Selected SAS StatementsStatement RETAIN Examples :

    This RETAIN statement retains the values of variables MONTH1 through MONTH5 from oneiteration of the DATA step to the next:

    retain month1-month5;

    This RETAIN statement retains the values of nine variables and sets their initial values:

    retain month1-month5 1 year 0 a b c 'XYZ';The values of MONTH1 through MONTH5 are set initially to 1; YEAR is set to 0; variables A, B, and

    C are each set to the character value

    XYZ.

    This RETAIN statement assigns the initial value 1 to the variable MONTH1 only:

    retain month1-month5 (1);

    Variables MONTH2 through MONTH5 are set to missing initially.

    Observations are ordered by the name of the month in which the expenses were accrued:

    by month notsorted;

  • 8/6/2019 Complete Sas

    92/284

    SAS Training 92

    Selected SAS Statements OUTPUT : Writes the current observation to a SAS data set

    Syntax

    OUTPUT;

    Without Arguments

    Using OUTPUT without arguments causes the current observation to be written to all data sets that are named inthe DATA statement.

    Arguments

    data-set-name

    specifies the name of a data set to which SAS writes the observation.

    Details:

    The OUTPUT statement tells SAS to write the current observation to a SAS data set immediately, not at the end ofthe DATA step. If no data set name is specified in the OUTPUT statement, the observation is written to the dataset or data sets that are listed in the DATA statement.

  • 8/6/2019 Complete Sas

    93/284

    SAS Training 93

    Selected SAS StatementsStatement OUTPUT Examples :

    These examples show how you can use an OUTPUT statement:

    /* writes the current observation */

    /* to a SAS data set */

    output; /* writes the current observation */

    /* when a condition is true */

    if deptcode gt 2000 then output; /* writes an observation to data */

    /* set MARKUP when the PHONE */

    /* value is missing */if phone=. then output markup;

  • 8/6/2019 Complete Sas

    94/284

    SAS Training 94

    Selected SAS Statements PUT : Writes lines to the SAS log, to the SAS procedure output file, or to an external file

    that is specified in the most recent FILE statementSyntax

    PUT ;

    Without Arguments

    The PUT statement without arguments is called a null PUT statement.

    The null PUT statement writes the current output line to the current file, even if the current output line is blank. releases an output line that is being held by a previous PUT statement with a trailing @.

  • 8/6/2019 Complete Sas

    95/284

    SAS Training 95

    Selected SAS Statements

    GlobalStatements LIBNAME : Associates or disassociates a SAS

    data library with a libref (a shortcut name);

    clears one or all librefs; lists thecharacteristics of a SAS data library;concatenates SAS data libraries; implicitlyconcatenates SAS catalogs.

    Syntax1. LIBNAME libref 'SAS-data-library'

    < options > ;

  • 8/6/2019 Complete Sas

    96/284

    SAS Training 96

    Selected SAS StatementsArguments

    libref

    is a shortcut name or a "nickname" for the aggregate storage location where your SASfiles are stored. It is any SAS name when you are assigning a new libref. When youare disassociating a libref from a SAS data library or when listing attributes, specifya libref that was previously assigned.

    'SAS-data-library'

    must be the physical name for the SAS data library. The physical name is thename that is recognized by the operating environment. Enclose the physical name insingle or double quotation marks.

    library-specification

    is two or more SAS data libraries, specified by physical names, previously-assignedlibrefs, or a combination of the two. Separate each specification with either a blank or acomma and enclose the entire list in parentheses.

  • 8/6/2019 Complete Sas

    97/284

    SAS Training 97

    Selected SAS Statements engine

    is an engine name.

    Details:

    The association between a libref and a SAS data library lasts only for the

    duration of the SAS session or until you change it or discontinue it withanother LIBNAME statement. The simplest form of the LIBNAME statementspecifies only a libref and the physical name of a SAS data library:

  • 8/6/2019 Complete Sas

    98/284

    SAS Training 98

    Selected SAS StatementsStatement LIBNAME Examples :

    Assigning and Using a Libref

    This example assigns the libref SALES to an aggregate storagelocation that is specified in quotation marks as a physical pathname.

    The DATA step creates SALES.QUARTER1 and stores it in that

    location. The PROC PRINT step references it by its two-level name,SALES.QUARTER1

    libname sales 'SAS-data-library';

    data sales.quarter1;

    infile 'your-input-file;

    input salesrep $20. +6 jansales febsales

    marsales;run;

    proc print data=sales.quarter1;

    run;

  • 8/6/2019 Complete Sas

    99/284

    SAS Training 99

    Selected SAS Statements TITLE : Specifies title lines for SAS output

    Syntax

    TITLE ;

    Without Arguments

    Using TITLE without arguments cancels all existing titles.

    Arguments

    n

    specifies the relative line that contains the title line.

    'text' | "text"specifies text that is enclosed in single or double quotation marks.

    Details:

    A TITLE statement takes effect when the step or RUN group with which it is associated executes. Once you specify a titlefor a line, it is used for all subsequent output until you cancel the title or define another title for that line. A TITLEstatement for a given line cancels the previous TITLE statement for that line and for all lines with larger n numbers.

  • 8/6/2019 Complete Sas

    100/284

    SAS Training 100

    Selected SAS StatementsStatement TITLE Examples :

    This statement suppresses a title on line n and all lines after it:

    titlen;

    These are examples of TITLE statements:

    title 'First Draft'; title2 "Year's End Report"; title2 'Year''s End Report';

    These statements illustrate #BYVAL, #BYVAR, and #BYLINE.

    title 'Quarterly Sales for #byval(site)'; title 'Annual Costs for #byvar2'; title 'Data Group #byline';

  • 8/6/2019 Complete Sas

    101/284

    SAS Training 101

    Selected SAS Statements FOOTNOTE : Prints up to ten lines of text at the bottom of the procedure or DATA step

    outputSyntax

    FOOTNOTE ;

    Without Arguments

    Using FOOTNOTE without arguments cancels all existing footnotes.

    Arguments

    n

    specifies the relative line to be occupied by the footnote.

    'text' | "text"

    specifies the text of the footnote in single or double quotation marks.

  • 8/6/2019 Complete Sas

    102/284

    SAS Training 102

    Selected SAS StatementsDetails:

    A FOOTNOTE statement takes effect when the step or RUN group withwhich it is associated executes. Once you specify a footnote for a line,SAS repeats the same footnote on all pages until you cancel or redefinethe footnote for that line. When a FOOTNOTE statement is specified fora given line, it cancels the previous FOOTNOTE statement for that lineand for all footnote lines with higher numbers.

    Statement FOOTNOTE Examples :

    These examples of a FOOTNOTE statement result in the samefootnote:

    footnote8 "Managers' Meeting";

    footnote8 'Managers'' Meeting';

  • 8/6/2019 Complete Sas

    103/284

    SAS Training 103

    SAS Options

    Definition of Options

    Data set options specify actions that apply only to the SAS data set with which theyappear. They let you perform such operations as

    renaming variables selecting only the first or last n observations for processing dropping variables from processing or from the output data set

    specifying a password for a SAS data set.

  • 8/6/2019 Complete Sas

    104/284

    SAS Training 104

    Syntax of Options Specify a data set option in parentheses after a SAS data set name. To

    specify several data set options, separate them with spaces.

    (option-1=value-1)

    These examples show data set options in SAS statements:

    data scores(keep=team game1 game2 game3); proc print data=new(drop=year); set old(rename=(date=Start_Date));

  • 8/6/2019 Complete Sas

    105/284

    SAS Training 105

    Selected SAS Options

    DROP : Excludes variables from processing or from output SASdata sets.

    Syntax

    DROP=variable(s)

    Syntax Description

    variable(s)

    lists one or more variable names. You can list the variables in any form that SASallows.

    Details : If the option is associated with an input data set, the variables are notavailable for processing. If the DROP= data set option is associated with an outputdata set, SAS does not write the variables to the output data set, but they areavailable for processing.

  • 8/6/2019 Complete Sas

    106/284

    SAS Training 106

    Selected SAS OptionsOption DROP Example :

    Excluding Variables from Input

    In this example, the variables SALARY and GENDER are not included inprocessing and they are not written to either output data set:

    data plan1 plan2;

    set payroll(drop=salary gender);

    if hired

  • 8/6/2019 Complete Sas

    107/284

    SAS Training 107

    Selected SAS Options

    KEEP : Specifies variables for processing or for writing to output SASdata sets

    Syntax

    KEEP=variable(s)

    Syntax Descriptionvariable(s)

    lists one or more variable names. You can list the variables in any form that SASallows.

    Details : If the KEEP= data set option is associated with an input data set, only thosevariables that are listed after the KEEP= data set option are available for processing. Ifthe KEEP= data set option is associated with an output data set, only the variables

    listed after the option are written to the output data set, but all variables are availablefor processing.

  • 8/6/2019 Complete Sas

    108/284

    SAS Training 108

    Selected SAS OptionsOption KEEP Example :

    In this example, only IDNUM and SALARY are read from PAYROLL,and they are the only variables in PAYROLL that are available forprocessing:

    data bonus;

    set payroll(keep=idnum salary);

    bonus=salary*1.1;

    run;

  • 8/6/2019 Complete Sas

    109/284

    SAS Training 109

    Selected SAS Options

    RENAME : Changes the name of a variable.

    Syntax

    RENAME=(old-name-1=new-name-1 < . . . old-name-n=new- name-n>)

    Syntax Description

    old-namethe variable you want to rename.

    new-name

    the new name of the variable. It must be a valid SAS name.

    Details : If you use the RENAME= data set option when you create a data set, the newvariable name is included in the output data set. If you use RENAME= on an input dataset, the new name is used in DATA step programming statements.

  • 8/6/2019 Complete Sas

    110/284

    SAS Training 110

    Selected SAS OptionsOption RENAME Example :

    Renaming a Variable at Time of Output

    This example uses RENAME= in the DATA statement to show thatthe variable is renamed at the time it is written to the output dataset. The variable keeps its original name, X, during the DATA stepprocessing:

    data two(rename=(x=keys));

    set one;

    z=x+y;

    run;

  • 8/6/2019 Complete Sas

    111/284

    SAS Training 111

    Selected SAS Options

    FIRSTOBS : Causes processing to begin at a specified observation.

    Syntax

    FIRSTOBS=n

    Syntax Description

    n

    is a positive integer that is less than or equal to the number of observationsin the data set.

    Details :The FIRSTOBS= data set option is valid when an existing SAS data set is read.You cannot use this option when a WHERE statement or WHERE= data set option isspecified in the same DATA or PROC step.

  • 8/6/2019 Complete Sas

    112/284

    SAS Training 112

    Selected SAS OptionsOption FIRSTOBS Example :

    This PROC step prints the data set STUDY beginning withobservation 20:

    proc print data=study(firstobs=20);

    run; This SET statement uses both FIRSTOBS= and OBS= to read only

    observations 5 through 10 from the data set STUDY. Data set NEWcontains six observations.

    data new;

    set study(firstobs=5 obs=10);

    run;

  • 8/6/2019 Complete Sas

    113/284

    SAS Training 113

    Selected SAS Options

    OBS : Causes processing to end with the nth observation.

    Syntax

    OBS=n|MAX

    Syntax Description

    nspecifies a positive integer that is less than or equal to the number of

    observations in the data set or zero.

    MAX

    represents the total number of observations in the data set.

    Details :This option specifies the number of the last observation to process, not howmany observations should be processed. It is valid only when an existing SAS data setis read.

    Use OBS=0 to create an empty data set that has the structure, but not the attributes,of another data set.

  • 8/6/2019 Complete Sas

    114/284

    SAS Training 114

    Selected SAS OptionsOption OBS Example :

    In this example, the OBS= data set option in the SET statementreads in the first ten observations from data set OLD:

    data new;

    set old(obs=10);run;

    This statement prints only observations 5 through 10 in data setSTUDY:

    proc print data=study(firstobs=5 obs=10);

  • 8/6/2019 Complete Sas

    115/284

    SAS Training 115

    Selected SAS Options

    WHERE : Selects observations that meet the specified condition

    Syntax

    WHERE=(where-expression)

    Syntax Description

    where-expression

    is an arithmetic or logical expression that consists of a sequence ofoperators, operands, and SAS functions. The expression must be enclosed inparentheses.

    Details : Use the WHERE= data set option with an input data set to selectobservations that meet the condition specified in the WHERE expression beforeSAS brings them into the DATA or PROC step for processing. Selectingobservations that meet the conditions of the WHERE expression is the first

    operation SAS performs in each iteration of the DATA step.

  • 8/6/2019 Complete Sas

    116/284

    SAS Training 116

    Selected SAS OptionsOption WHERE Example :

    Selecting Observations from an Input Data Set

    This example uses the WHERE= data set option to subset the SALESdata set as it is read into another data set:

    data whizmo;set sales(where=(product='whizmo'));

    run; Selecting Observations from an Output Data Set

    This example uses the WHERE= data set option to subset the SALESoutput data set:

    data whizmo(where=(product='whizmo'));

    set sales;

    run;

  • 8/6/2019 Complete Sas

    117/284

    SAS Training 117

    SAS Format

    Definition of Format

    A format is an instruction that SAS uses to write data values. You useformats to control the written appearance of data values, or, in some

    cases, to group data values together for analysis. For example, theWORDS22. format, which converts numeric values to their equivalentin words, writes the numeric value 692 as six hundred ninety-two

  • 8/6/2019 Complete Sas

    118/284

  • 8/6/2019 Complete Sas

    119/284

    SAS Training 119

    Selected SAS Formats

    $CHARw: Writes standard character data.

    Syntax

    $CHARw.

    Syntax Description

    w

    specifies the width of the output field.

  • 8/6/2019 Complete Sas

    120/284

    SAS Training 120

    Selected SAS FormatsFormat $CHARw Example :

    put @7 name $char4.;

    Values Results

    ----+----1

    XYZ XYZ

  • 8/6/2019 Complete Sas

    121/284

    SAS Training 121

    Selected SAS Formats

    $w: Writes standard character data.

    Syntax

    $w.

    Syntax Description

    w

    specifies the width of the output field. You can specify anumber or a column range.

  • 8/6/2019 Complete Sas

    122/284

    SAS Training 122

    Selected SAS FormatsFormat $w Example :

    put @10 name $5.;

    put name $ 10-15;

    Values Results

    ----+----1----+----2

    #Cary Cary

    Tokyo Tokyo

    *The character # represents ablank space.

  • 8/6/2019 Complete Sas

    123/284

    SAS Training 123

    Selected SAS Formats

    DOLLARw.d: Writes numeric values with dollar signs, commas, anddecimal pointsSyntax

    DOLLARw.d

    Syntax Description

    wspecifies the width of the output field.

    d

    optionally specifies the number of digits to the right of the decimal point in thenumeric value.

    Details:The DOLLARw.dformat writes numeric values with a leading dollar sign, with a commathat separates every three digits, and a period that separates the decimal fraction

  • 8/6/2019 Complete Sas

    124/284

    SAS Training 124

    Selected SAS FormatsFormat DOLLARw.d Example :

    put @3 netpay dollar10.2;

    Values Results

    ----+----1----+

    1254.71 $1,254.71

  • 8/6/2019 Complete Sas

    125/284

    SAS Training 125

    SAS Informat

    Definition of Informat

    An informat is an instruction that SAS uses to read data values into avariable.

    Unless you explicitly define a variable first, SAS uses the informat todetermine whether the variable is numeric or character. SAS also uses theinformat to determine the length of character variables.

  • 8/6/2019 Complete Sas

    126/284

    SAS Training 126

    Syntax of Informat SAS Informats have the following form:

    informat.

    where

    $

    indicates a character format; its absence indicates a numeric format.informat

    names the informat.

    w

    specifies the informat width, which for most informats is the number of columnsin the input data.

    d

    specifies an optional decimal scaling factor in the numeric informats.SASdivides the input data by 10 to the power of d.

  • 8/6/2019 Complete Sas

    127/284

    SAS Training 127

    Selected SAS Informats

    $CHARw: Reads character data with blanks.

    Syntax

    $CHARw.

    Syntax Description

    w

    specifies the width of the input field.

    Details:The $CHARw. informat does not trim leading and trailing blanks or convert asingle period in the input data field to a blank before storing values. If you use$CHARw. in an INFORMAT or ATTRIB statement within a DATA step to read list input,then by default SAS interprets any blank embedded within data as a field delimiter,

    including leading blanks.

  • 8/6/2019 Complete Sas

    128/284

    SAS Training 128

    Selected SAS FormatsInformat $CHARw Example :

    put @1 name $char5.;

    Data lines Results

    ----+----1

    XYZ XYZ##

    XYZ #XYZ#

    . ##.##

    X YZ #X#YZ

    *The character # represents ablank space

  • 8/6/2019 Complete Sas

    129/284

    SAS Training 129

    Selected SAS Informats

    $w: Reads standard character data.

    Syntax

    $w.

    Syntax Descriptionw

    specifies the width of the input field. You must specify w because SASdoes not supply a default value.

    Details:The $w. informat trims leading blanks and left aligns the values beforestoring the text. In addition, if a field contains only blanks and a single period,$w. converts the period to a blank because it interprets the period as a missingvalue. The $w. informat treats two or more periods in a field as character data.

  • 8/6/2019 Complete Sas

    130/284

    SAS Training 130

    Selected SAS InformatsFormat $w Example :

    input @1 name $5.;

    Data lines Results

    ----+----1

    XYZ XYZ##

    XYZ XYZ##

    .

    X YZ X#YZ#

    *The character # represents ablank space

  • 8/6/2019 Complete Sas

    131/284

    SAS Training 131

    SAS Procedures

    Print Format

    Sort Append ContentsTranspose SQL

  • 8/6/2019 Complete Sas

    132/284

    SAS Training 132

    Proc Print

    The PRINT procedure prints the

    observations in a SAS data set,using all or some of thevariables.

  • 8/6/2019 Complete Sas

    133/284

    SAS Training 133

    Syntax

    PROC PRINT

  • 8/6/2019 Complete Sas

    134/284

    SAS Training 134

    Hands-On Exercise

    Create a List Report from the Cake Datasetdisplaying the first 10 Observations

    Expected Output:

  • 8/6/2019 Complete Sas

    135/284

    SAS Training 135

    Solution

    procprintdata = cake (obs=10);

    var lastname flavor pscore;

    run;

  • 8/6/2019 Complete Sas

    136/284

    SAS Training 136

    User Defined Format

    Proc Format

    The FORMAT procedure enables

    you to define your own informatsand formats for variables.

  • 8/6/2019 Complete Sas

    137/284

    SAS Training 137

    Syntax

    PROC FORMAT ;

    VALUE name value-range-set(s);

  • 8/6/2019 Complete Sas

    138/284

    SAS Training 138

    Example

    Proc Format; value $genders m=Male f=Female Run;

    Proc Print data=customer.demo;format sex $gender.;

    run;

  • 8/6/2019 Complete Sas

    139/284

    d O i

  • 8/6/2019 Complete Sas

    140/284

    SAS Training 140

    Hands-On Exercise

    Display the values of the variable SEX in Classdataset as 1 and 2 , instead of the default values.

    H d O E i

  • 8/6/2019 Complete Sas

    141/284

    SAS Training 141

    Hands-On Exercise

    Expected Output

    S l i

  • 8/6/2019 Complete Sas

    142/284

    SAS Training 142

    Solution

    procformat;

    value $sex 'M' = 1

    'F' = 2

    ;

    run;

    procprintdata = train.class;format sex $sex.;

    run;

    P S t

  • 8/6/2019 Complete Sas

    143/284

    SAS Training 143

    Proc Sort

    The SORT procedure sorts

    observations in a SAS data set byone or more character or numericvariables, either replacing the

    original data set or creating anew, sorted data set.

    S t

  • 8/6/2019 Complete Sas

    144/284

    SAS Training 144

    Syntax

    PROC SORT

    BY variable-1;

    Options(s) :nodupkey

    E l

  • 8/6/2019 Complete Sas

    145/284

    SAS Training 145

    Example

    Company Debt Town

    Paul's Pizza 83.00 Apex

    Apex World WideElectronics

    119.95 Apex

    Garner StricklandIndustries

    657.22 Apex

    Morrisville Ice CreamDelight

    299.98 Apex

    Account

  • 8/6/2019 Complete Sas

    146/284

    SAS Training 146

    proc sort data=accountout=bytown;

    by town company;

    run;

    proc print data=bytown;

    var company town debt;title 'Customers with Past-DueAccounts';

    title2 'Listed Al habeticall

    O t t

  • 8/6/2019 Complete Sas

    147/284

    SAS Training 147

    Output

    Customers with Past-Due Accounts

    Listed Alphabetically within Town

    Obs Company TownDebt

    1 Apex World Wide Electronics Apex 119.95

    2 Garner Strickland Industries Apex 657.223 Morrisville Ice Cream Delight Apex 299.98

    4 Paul's Pizza Apex 83.00

    D li t b ti

  • 8/6/2019 Complete Sas

    148/284

    SAS Training 148

    proc sort data=account out=towns nodupkey;

    by town; run;

    proc print data=towns;

    var town company debt ;

    title 'Towns of Customers with Past-Due

    Accounts;

    run;

    Duplicate observations

    O t t

  • 8/6/2019 Complete Sas

    149/284

    SAS Training 149

    Towns of Customers with Past-Due Accounts

    Obs Town Company Debt

    1 Apex Paul's Pizza 83.00

    2 Garner World Wide Electronics 119.95

    3 Holly Springs Ice Cream Delight 299.98

    4 Morrisville Strickland Industries 657.22

    Output

    H d O E i

  • 8/6/2019 Complete Sas

    150/284

    SAS Training 150

    Hands-On Exercise

    SORT DUPOBS dataset to create dataset A. sort thedata by descending tourtype and vendor andascending landcostExpected Output

    S l ti

  • 8/6/2019 Complete Sas

    151/284

    SAS Training 151

    Solution

    procsortdata = dupobs ;

    bydescending tourtype descending

    vendor landcost;

    run;

    Proc Append

  • 8/6/2019 Complete Sas

    152/284

    SAS Training 152

    Proc Append

    The APPEND procedure adds the observations fromone SAS data set to the end of another SAS data set

    Remember:

    Both data sets contained the same variables. If Appending data sets with different variables,

    use the FORCE option

    Syntax

  • 8/6/2019 Complete Sas

    153/284

    SAS Training 153

    Syntax

    PROC APPEND

    BASE=SAS-data-set ;

  • 8/6/2019 Complete Sas

    154/284

    Example

  • 8/6/2019 Complete Sas

    155/284

    SAS Training 155

    Example

    PROC APPEND BASE=class1DATA=class2; RUN;

    Output

  • 8/6/2019 Complete Sas

    156/284

    SAS Training 156

    Outputname age height

    Andrew 15 67

    Robert 15 78

    Philip 14 70

    Andrea 16 60

    Linda 13 55

    Stephen 17 72

    Hands On - Exercise

  • 8/6/2019 Complete Sas

    157/284

    SAS Training 157

    Hands On Exercise

    Append datasets DEPT1 and DEPT2 and createreplace DEPT1 with the appended dataset

    Expected Output

    Solution

  • 8/6/2019 Complete Sas

    158/284

    SAS Training 158

    Solution

    procappendbase = dept1 data=dept2;

    run;

    procprintdata = dept1;

    run;

    Proc Contents

  • 8/6/2019 Complete Sas

    159/284

    SAS Training 159

    Proc Contents

    The CONTENTS procedure shows the contents of aSAS data set and prints the directory of the SAS datalibrary.

    Example

  • 8/6/2019 Complete Sas

    160/284

    SAS Training 160

    Example

    proc contents data=test.records;

    run;

    Output

  • 8/6/2019 Complete Sas

    161/284

    SAS Training 161

    Ou pu

    Hands On Exercise

  • 8/6/2019 Complete Sas

    162/284

    SAS Training 162

    Hands-On Exercise

    Display the Dataset structure of DUPOBS dataset

    Proc Transpose

  • 8/6/2019 Complete Sas

    163/284

    SAS Training 163

    p

    The TRANSPOSE procedure creates an output data setby restructuring the values in a SAS data set, transposingselected variables into observations.

    Original data Transposed data

    X Y Z _NAME_ COL1 COL2 COL3 COL4

    12 19 14 X 12 21 33 14

    21 15 19 =) Y 19 15 27 32

    33 27 82 Z 14 19 82 9914 32 99

    Syntax

  • 8/6/2019 Complete Sas

    164/284

    SAS Training 164

    Syntax

    PROC TRANSPOSE

  • 8/6/2019 Complete Sas

    165/284

    SAS Training 165

    statement

    Transpose each BY group BY

    Copy variables directly without

    transposing them

    COPY

    Specify a variable whose values name

    the transposed variables

    ID

    Create labels for the transposed

    variables

    IDLABEL

    List the variables to transpose VAR

    Hands-On Exercise

  • 8/6/2019 Complete Sas

    166/284

    SAS Training 166

    Transpose the dataset grp_tran in the Trainlibrary to get the output as shown below

    Solution

  • 8/6/2019 Complete Sas

    167/284

    SAS Training 167

    Solutionprocsortdata = grp_tran;

    by grp;

    run;

    proctransposedata = grp_tran out =result (drop= _name_);

    by grp;

    run;

    procprintdata = result;

    run;

    Proc SQL

  • 8/6/2019 Complete Sas

    168/284

    SAS Training 168

    The SQL procedure implementsStructured Query Language

    (SQL) for the SAS System. SQL isa standardized, widely usedlanguage that retrieves and

    updates data in tables and viewsbased on those tables

    Proc SQL

  • 8/6/2019 Complete Sas

    169/284

    Syntax

  • 8/6/2019 Complete Sas

    170/284

    SAS Training 170

    Syntax

    CONT.

    CREATE TABLE table-name (column-definition ...);

    (column-specification , ... ,...) ;

    DROP TABLE table-name ...;

    DROP VIEW view-name ...;

    INSERT INTO table-name|sas/access-view|proc-sql-view

    VALUES (value...)...;

    Syntax

  • 8/6/2019 Complete Sas

    171/284

    SAS Training 171

    SyntaxSELECT object-item ...

    FROM from-list

    ;

    Example

  • 8/6/2019 Complete Sas

    172/284

    SAS Training 172

    Example

    Proc Sql;

    select Lname, Fname, City, State,

    IdNumber, Salary, Jobcodefrom staff, payrollwhere idnumber=idnum ;

    Quit;

    Hands-On Exercise

  • 8/6/2019 Complete Sas

    173/284

    SAS Training 173

    Create Table for Females from the Classdataset using Proc Sql.

    Expected Output

  • 8/6/2019 Complete Sas

    174/284

    Proc GPLOT

  • 8/6/2019 Complete Sas

    175/284

    SAS Training 175

    The GPLOT procedure plots thevalues of two or more variables

    on a set of coordinate axes (Xand Y). The coordinates of eachpoint on the plot correspond to

    two variable values in anobservation of the input dataset.

    Proc GPLOT

    Syntax

  • 8/6/2019 Complete Sas

    176/284

    SAS Training 176

    Syntax

    PROC GPLOT

    ;

    PLOTplot-request(s) ;

    Example

  • 8/6/2019 Complete Sas

    177/284

    SAS Training 177

    Example

    procgplotdata = dupobs;

    goptionsreset = all;

    plot landcost*country;

    run;

    Output

  • 8/6/2019 Complete Sas

    178/284

    SAS Training 178

    Output

    Example

  • 8/6/2019 Complete Sas

    179/284

    SAS Training 179

    Example

    procgplotdata = dupobs;

    goptionsreset=all;

    symbol1 color = greenvalue=triangle ;

    symbol2color=blue value=circle;symbol3color=redvalue=square;

    plot landcost*country=vendor;

    run;

    Output

  • 8/6/2019 Complete Sas

    180/284

    SAS Training 180

    Output

  • 8/6/2019 Complete Sas

    181/284

    Syntax

  • 8/6/2019 Complete Sas

    182/284

    SAS Training 182

    Syntax

    PROC MEANS

    BY variable-1 ;

    CLASSvariable(s) ;

    OUTPUT

    PROC MEANS (OPTIONS)

  • 8/6/2019 Complete Sas

    183/284

    SAS Training 183

    PROC MEANS (OPTIONS)

    Specify the number of decimalplaces for the statistics

    MAXDEC=

    Suppress all displayed output NOPRINT

    Order the values of the classvariables according to the

    specified order

    ORDER=

    Limit the output statistics tothe observations with thehighest _TYPE_ value

    NWAY

    PROC MEANS (BY)

  • 8/6/2019 Complete Sas

    184/284

    SAS Training 184

    PROC MEANS (BY)Produces separate statistics for each BY group.

    proc sort data = temp; by cat;run;

    proc means data = temp;by cat;output out = temp1;run;

    Example: Input Dataset

    PROC MEANS (CLASS)

  • 8/6/2019 Complete Sas

    185/284

    SAS Training 185

    PROC MEANS (CLASS)

    Specifies the variables whose valuesdefine the subgroup combinations forthe analysis.

    PROC MEANS (NWAY)

  • 8/6/2019 Complete Sas

    186/284

    SAS Training 186

    PROC MEANS (NWAY)

    proc means data = prod nway;

    class cat product;

    var sales;

    output out = prodsta n=n sum=total;run;

    PROC MEANS (OUTPUT)

  • 8/6/2019 Complete Sas

    187/284

    SAS Training 187

    PROC MEANS (OUTPUT)Outputs statistics to a new SAS data set

    Input Data set

    proc means data = sales;class prod;output out = temp n = Cost_n sal_n mean=Cost_mSale_m;run;

    PROC MEANS (CLASS)

  • 8/6/2019 Complete Sas

    188/284

    SAS Training 188

    OC S (C SS)

    proc means data = prod;

    class cat product;

    var sales;

    output out = prodsta n=n sum=total; run;

    PROC MEANS (VAR)

  • 8/6/2019 Complete Sas

    189/284

    SAS Training 189

    ( )

    Identifies the analysis variables and theirorder in the output.

    If you omit the VAR statement, PROCMEANS analyzes all numeric variables that

    are not listed in the other statements.When all variables are character variables,PROC MEANS produces a simple count ofobservations.

  • 8/6/2019 Complete Sas

    190/284

    SAS Training 190

    PROC Summary

    The SUMMARY procedureprovides data summarizationtools that compute descriptivestatistics for variables across allobservations or within groups ofobservations

    Syntax

  • 8/6/2019 Complete Sas

    191/284

    SAS Training 191

    y

    PROC SUMMARY

  • 8/6/2019 Complete Sas

    192/284

    SAS Training 192

    y

    Both PROC MEANS and PROC SUMMARYcompute descriptive statistics for anentire SAS data set.

    The Difference Between them :. PROC MEANSproducessubgroup statistics onlywhen a BY statement isused and the input data

    has been previously sorted(use PROC SORT) by theBY variables

    PROC SUMMARYautomatically producesstatistics for all subgroups,giving you all the

    information in one run

    Difference Between ProcMeans & Proc Summary

  • 8/6/2019 Complete Sas

    193/284

    SAS Training 193

    .PROC MEANS produceinformation in the outputwindow.

    PROC SUMMARY does notproduce any information inyour output so you will alwaysneed to use the OUTPUT

    statement to create a newdata set and use PROCPRINT to see the computedstatistics.

    PROC REPORT

  • 8/6/2019 Complete Sas

    194/284

    SAS Training 194

    Overview:The REPORT procedure combines features ofthe PRINT, MEANS, and TABULATE procedures

    with features of the DATA step in a singlereport-writing tool that can produce a varietyof reports

    PROC REPORT (TYPES)

  • 8/6/2019 Complete Sas

    195/284

    SAS Training 195

    ( )

    PROC REPORT (TYPES)

  • 8/6/2019 Complete Sas

    196/284

    SAS Training 196

  • 8/6/2019 Complete Sas

    197/284

    SAS Training 197

  • 8/6/2019 Complete Sas

    198/284

    Typical Report Example

  • 8/6/2019 Complete Sas

    199/284

    SAS Training 199

    yp p p

    Input Data set

    proc report data = rep nowd headlineheadskip;column product sales;

    define product / 'Product Name' order;define sales / 'Sales Occured' format=8.2;run;

    PROC REPORT (Syntax)

  • 8/6/2019 Complete Sas

    200/284

    SAS Training 200

    y

    PROC REPORT ;

    BY variable-1COLUMNcolumn-specification(s);

    COMPUTE

    LINEspecification(s); . . . select SAS

    language elements . . .ENDCOMP;

    DEFINEreport-item ;

    REBREAK l ti ti

    PROC REPORT (OPTIONS)

  • 8/6/2019 Complete Sas

    201/284

    SAS Training 201

    Select the windowing or the nonwindowingenvironment

    WINDOWS|NOWINDOWS

    Specify the default number of characters forcolumns containing computed variables ornumeric data set variables

    COLWIDTH=

    Underline all column headers and the spacesbetween them

    HEADLINE

    Write a blank line beneath all column headers HEADSKIP

    Specify the split character SPLIT=

    Specify the number of blank charactersbetween columns

    SPACING=

    PROC REPORT (COLUMN)

  • 8/6/2019 Complete Sas

    202/284

    SAS Training 202

    Describes the arrangement of all columnsand of headers that span more than onecolumn.

    column-specification(s) is one or more ofthe following: report-item(s) report-item-1, report-item-2 (`header-1 ' < . . . `header-n '> report-item(s) ) report-item=name

    PROC REPORT (COLUMN)

  • 8/6/2019 Complete Sas

    203/284

    SAS Training 203

    Examples

    column sector manager N sales;

    column sector sales,min;

    column ('Individual Store Sales as aPercent of All Sales' sector manager);

    column manager department sales

    sales=salesmin sales=salesmax;

    PROC REPORT

  • 8/6/2019 Complete Sas

    204/284

    SAS Training 204

    Decide the usage of a variable inDEFINE statement

    these usages are DISPLAY

    ORDER

    ACROSS GROUP

    ANALYSIS

    PROC REPORT (DEFINE)

  • 8/6/2019 Complete Sas

    205/284

    SAS Training 205

    DISPLAY Do not affect the order ofvariables in a row

    ORDER Used to change order of variables

    (Ascending/Descending/Formatted) ACROSS - creates a column for each value

    of an across variable. GROUP Creates Groups

    Analysis To calculate statistics Computed Variables defined for the report

    not on input data set

  • 8/6/2019 Complete Sas

    206/284

    PROC REPORT (BREAK)

  • 8/6/2019 Complete Sas

    207/284

    SAS Training 207

    Produces a default summary at thebeginning or end of a report or at thebeginning and end of each BY group.

    RBREAKlocation ;

    Write a blank line for the last break line of a breaklocated at the beginning of the report

    SKIP

    Include a summary line as one of the break lines SUMMARIZE

    Start a new page after the last break line of a breaklocated at the beginning of the report

    PAGE

    Example

  • 8/6/2019 Complete Sas

    208/284

    SAS Training 208

    Input Data set

    proc report data = rep nowd headline headskipsplit='*';column ('This is sales report' product N salessales,min discount newprice);define product / 'Product Name' group;define sales / 'My*Sales' format=8.2;define min / 'Min';define newprice / 'Discount Price' computed;

    compute newprice;newprice = _c3_ - _c5_;

    endcomp;

    break after product / skip;run;

  • 8/6/2019 Complete Sas

    209/284

    SAS Date

  • 8/6/2019 Complete Sas

    210/284

    SAS Training 210

    How SAS Converts Calendar Dates toSAS

    Date Values :

    SAS Date

  • 8/6/2019 Complete Sas

    211/284

    SAS Training 211

    Working with SAS Dates :The SAS System converts date values back and forth

    between calendar dates with SAS languageelements called formats and informats.

    Formats present a value, recognized by SAS, suchas a date value, as a calendar date in a variety oflengths and notations.

    Informats read notations or a value, such as acalendar date, which may be in a variety of lengths,and then convert the data to a SAS date.

    SAS Date

  • 8/6/2019 Complete Sas

    212/284

    SAS Training 212

    Example: Reading, Writing, andCalculating Date Values

    data meeting;

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

    input region $ mtg : mmddyy8.;

    sendmail=mtg-45;

    datalines;

    N 11-24-99

    S 12-28-99

    E 12-03-99

    W 10-04-99;

    SAS Date

  • 8/6/2019 Complete Sas

    213/284

    SAS Training 213

    proc print data=meeting;

    format mtg sendmail date9.;

    title 'When To Send Announcements';

    run;

    SAS Date

  • 8/6/2019 Complete Sas

    214/284

    SAS Training 214

    Date formats

    DATEw. Format: Writes date values in theform ddmmmyyor ddmmmyyyy.

    Syntax :

    DATEw.

    SAS Date

  • 8/6/2019 Complete Sas

    215/284

    SAS Training 215

    ExamplesThe example table uses the input value of 15415, which is

    the

    SAS date value that corresponds to March 16, 2002.

    SAS Date

  • 8/6/2019 Complete Sas

    216/284

    SAS Training 216

    DDMMYYw. Format : Writes date values in theform ddmmyyor ddmmyyyy.

    Syntax

    DDMMYYw.

    SAS Date

  • 8/6/2019 Complete Sas

    217/284

    SAS Training 217

    Examples :The example table uses the input value of 15415,which is

    the SAS date value that corresponds to March 16, 2002.

    SAS Date

  • 8/6/2019 Complete Sas

    218/284

    SAS Training 218

    Date Informats

    DATEw. : Reads date values in the formddmmmyyor ddmmmyyyy.

    Syntax

    DATEw.

    SAS Date

  • 8/6/2019 Complete Sas

    219/284

    SAS Training 219

    Example :

    input calendar_date date11.;

    SAS Date

  • 8/6/2019 Complete Sas

    220/284

    SAS Training 220

    DDMMYYw. Informat :Reads datevalues in

    the form ddmmyyor ddmmyyyy.

    Syntax

    DDMMYYw.

    SAS Date

  • 8/6/2019 Complete Sas

    221/284

    SAS Training 221

    Example :

    input calendar_date ddmmyy10.;

    SAS Date

  • 8/6/2019 Complete Sas

    222/284

    SAS Training 222

    Functions

    DATE Function : Returns the current date as a SAS date value

    Syntax :

    DATE()

    Details :The DATE function produces the current date

    in the form of a SAS date value, which is the number of

    days since January 1, 1960.

    SAS Date

  • 8/6/2019 Complete Sas

    223/284

    SAS Training 223

    Example :

    tday=date();Put tday ddmmyy8.;

    SAS Date

  • 8/6/2019 Complete Sas

    224/284

    SAS Training 224

    TODAY function : Returns the current date as a SASdate value.

    Syntax :

    TODAY()

    Details :TODAY is identical to the DATE function.

    The TODAY function produces the current date

    in the form of a SAS date value, which is the number of

    days since January 1, 1960.

    SAS Date

  • 8/6/2019 Complete Sas

    225/284

    SAS Training 225

    YEAR function : Returns the year from a SAS date value.

    Syntax :

    YEAR(date)

    Details :The YEAR function produces a four-digit numeric value thatrepresents the year.

    SAS Date

  • 8/6/2019 Complete Sas

    226/284

    SAS Training 226

    Example :

    SAS Date

  • 8/6/2019 Complete Sas

    227/284

    SAS Training 227

    MONTH function : Returns the month from a

    SAS date value.

    Syntax :

    MONTH(date)

    Details :The MONTH function returns a numeric valuethat represents the month from a SAS date value.

    Numeric values can range from 1 through 12.

    SAS Date

  • 8/6/2019 Complete Sas

    228/284

    SAS Training 228

    Example :

  • 8/6/2019 Complete Sas

    229/284

    SAS Date

  • 8/6/2019 Complete Sas

    230/284

    SAS Training 230

    Example :

    SAS Date

  • 8/6/2019 Complete Sas

    231/284

    SAS Training 231

    QTR function: Returns the quarter of the year from a SASdate value.

    Syntax :

    QTR(date)

    Details :The QTR function returns a value of

    1, 2, 3, or 4 from a SAS date value to indicate

    the quarter of the year in which a date value

    falls.

    SAS Date

  • 8/6/2019 Complete Sas

    232/284

    SAS Training 232

    Example :

    SAS Date

  • 8/6/2019 Complete Sas

    233/284

    SAS Training 233

    WEEKDAY Function : Returns the day of the week from a SASdate value.

    Syntax :

    WEEKDAY(date)

    Details : The WEEKDAY function produces an integer

    that represents the day of the week, where 1=Sunday,

    2=Monday, . . . , 7=Saturday.

    SAS Date

  • 8/6/2019 Complete Sas

    234/284

    SAS Training 234

    Example :

    SAS Date

  • 8/6/2019 Complete Sas

    235/284

    SAS Training 235

    MDY Function :Returns a SAS date valuefrom month, day, and year values.

    Syntax :

    MDY(month,day,year)

    SAS Date

  • 8/6/2019 Complete Sas

    236/284

    SAS Training 236

    Example :

  • 8/6/2019 Complete Sas

    237/284

    SAS Training 237

    INTRODUCTION TOMACROS

    What is a Macro Facility?

  • 8/6/2019 Complete Sas

    238/284

    SAS Training 238

    The macro facility is a tool forextending and customizing theSAS System and for reducing theamount of text you must enterto do common tasks

    Replacing Text Strings Using Macro Variables

  • 8/6/2019 Complete Sas

    239/284

    SAS Training 239

    Macro variables are an efficient way of replacingtext strings in SAS code

    The Simplest way to define a macro variable is touse the %LET statement to assign the macrovariable a name and a value.

    Eg:%let macname = Test;

    Replacing Text Strings Using Macro Variables

  • 8/6/2019 Complete Sas

    240/284

    SAS Training 240

    Resolve a Macro Variable Value using the &symbol

    Eg:

    %let macname = Test;

    title This is a &macname

    The macro processor resolves the reference tothe macro variable MACNAME, and thestatement becomes

    Title This is a Test

    Generating SAS Code Using Macros

  • 8/6/2019 Complete Sas

    241/284

    SAS Training 241

    Macros Allow you to execute a SAS code multipletimes without compiling it.

    A macro definition is placed between a %MACRO

    statement and a %MEND (macro end) statement,as follows:

    %MACRO macro-name;

    SAS code

    %MEND macro-name;

    Execute the macro using %macro-name

    Generating SAS Code Using Macros

  • 8/6/2019 Complete Sas

    242/284

    SAS Training 242

    Eg:

    %macro mac1;

    data temp1;

    set temp;

    x= Hello;

    run;

    %mend mac1;

    %mac1;

    Execution of this macro produces the following

    Generating SAS Code Using Macros

  • 8/6/2019 Complete Sas

    243/284

    SAS Training 243

    Execution of this macro produces thefollowing program:

    data temp1;

    set temp;

    x= Hello;

    run;

  • 8/6/2019 Complete Sas

    244/284

    SAS Training 244

    Hands On Exercise

    Create a macro datcrt thatcreates a data set cake1 from

    train.cake

    Solution

  • 8/6/2019 Complete Sas

    245/284

    SAS Training 245

    %macro datcrt;

    data cake1;

    set train.cake;run;

    %macro datcrt;

    %datcrt;

    Passing Information into a Macro UsingParameters

  • 8/6/2019 Complete Sas

    246/284

    SAS Training 246

    A macro variable defined in parentheses in a%MACRO statement is a macro parameter

    Macro parameters allow you to pass informationinto a macro

    Passing Information into a Macro UsingParameters

  • 8/6/2019 Complete Sas

    247/284

    SAS Training 247

    Eg:

    %macro mac2 (dest= , src = );

    data &src;

    set &dest;

    x= Hello;

    run;

    You invoke the macro by providing values for the parameters, asfollows:

    %mac2 (dest=temp1, src=temp) ;

    %mac2 (dest=temp2, src=temp);

  • 8/6/2019 Complete Sas

    248/284

    SAS Training 248

    Hands On Exercise

    Create a Macro datprnt thatprints the data set cake and

    dept1 when passed as a macro

    parameter

    Solution

  • 8/6/2019 Complete Sas

    249/284

    SAS Training 249

    %macro datprnt (dat= );

    proc print data = &dat;

    run;%mend datprnt;

    %datprnt (dat=cake);

    %datprnt (dat=dept1);

    Conditionally Generating SAS Code

    U %IF %THEN %ELSE t t t t

  • 8/6/2019 Complete Sas

    250/284

    SAS Training 250

    Use %IF-%THEN-%ELSE macro statements toconditionally generate SAS code with a macro.

    Eg:

    %macro test (info= , mydata = );

    %if &info = print %then %do;

    proc print data = &mydata; run;

    %end;

    %else %if &info = report %then %do;

    proc report data = &mydata; run;

    %end;

    %mend test;

    Conditionally Generating SAS Code

  • 8/6/2019 Complete Sas

    251/284

    SAS Training 251

    %test(info=print,mydata = data1); /* Callingthe Macro */

    Result of the macro execution:Proc print data = data1;

    run;

    Macro Variables

    Macro variables are tools that enable you to dynamically modify the

  • 8/6/2019 Complete Sas

    252/284

    SAS Training 252

    Macro variables are tools that enable you to dynamically modify thetext in a SAS program through symbolic substitution.

    You can assign large or small amounts of text to macro variables, andafter that, you can use that text by simply referencing the variable thatcontains it.

    Macro variables defined by macro programmers are called user-defined

    macro variables.Eg: %let name = Henry Woodbridge is Male;

    Those defined by the SAS System are called automatic macro variables

    Eg: Sysdate,Sysday, SysProcessID, etc.

    Methods to create User Defined Macro Variables

    %L t

  • 8/6/2019 Complete Sas

    253/284

    SAS Training 253

    %Let iterative %DO statement %GLOBAL statement

    %INPUT statement INTO clause of the SELECT statement in SQL %LOCAL statement %MACRO statement

    SYMPUT routine %WINDOW statement.

    After a macro variable is created you typically use the variable by

    Using Macro Variables

  • 8/6/2019 Complete Sas

    254/284

    SAS Training 254

    After a macro variable is created, you typically use the variable byreferencing it with an ampersand preceding its name (&variable-name), which is called a macro variable reference.

    These references perform symbolic substitutions when they resolve totheir value.

    Eg:%let dsn=Newdata;title1 "Contents of Data Set &dsn";

    data temp;

    set &dsn;

    if age>=20;

    run;

    Using Macro Variables

    if macro variable JERRY is misspelled as JERY the following

  • 8/6/2019 Complete Sas

    255/284

    SAS Training 255

    if macro variable JERRY is misspelled as JERY, the followingproduces an unexpected result:

    %let jerry=student;

    data temp;

    x="produced by &jery";

    run;This produces the following message:

    WARNING: Apparent symbolic reference JERY not resolved.

    Note: Display the macro variable value using %put

    Eg:

    %put &jerry;

    Combining Macro Variable References withText

    When the macro variable is appended after a text

  • 8/6/2019 Complete Sas

    256/284

    SAS Training 256

    DATA=PERSNL&YR.EMPLOYES, where &YR contains two characters for a year

    Data = &MONTH&YR%let name=sales;

    data new&name;

    set save.&name;

    more SAS statements

    run;

    The SAS system sees it as

    DATA NEWSALES;

    SET SAVE.SALES;

    more SAS statements

    RUN;

    When the macro variable is appended after a text,directly reference it with the text.

    When a text is appended after a macro variable, usethe delimiter . between the macro variable referenceand the text

    Combining Macro Variable References withText

    Eg

  • 8/6/2019 Complete Sas

    257/284

    SAS Training 257

    Eg:DATA=PERSNL&YR.EMPLOYES, where &YR contains two character