SAS logo

Demo Steps for SAS® Programming 1: Essentials


Course Code: EPG1V2, prepared date: June 19, 2023
Copyright © SAS Institute Inc., Cary, NC, USA. All rights reserved.

Lesson 00, Section 0 Demo: The SAS Programming Process


We recommend that you view this demo rather than perform the steps in your software. You can come back and perform the steps only after you complete the data setup for this course.

The Excel workbook Storm.xlsx contains the storm data that is used in the demonstrations. It includes the following worksheets:

  • Storm_Summary contains one row per storm between 1980 and 2016. Wind speeds are measured in miles per hour (MPH).
    Note: Refer to the Basin_Codes, SubBasin_Codes, and Type_Codes worksheets for the full names of the codes in the respective fields.
  • Storm_Detail contains one measurement for every six hours of a storm. Wind speeds are measured in knots.
  • Storm_Damage includes a description and damage estimates (adjusted for inflation) for storms in the US with damages greater than one billion dollars.
  • Storm_Range contains one row per storm with a minimum of four wind measurements. The top four wind measurements are in columns Wind1 through Wind4.
  • Storm_2017 contains one row per storm for 2017.
  • Basin_Codes, SubBasin_Codes, and Type_Codes are lookup tables with codes and descriptive values.

  1. Start either SAS Studio or SAS Enterprise Guide. You must have your data set up and the PG1 library defined. If you are using SAS Studio, run the setup.sas program in your EPG1V2 folder. If you are using SAS Enterprise Guide, run the Autoexec process flow when you are prompted to do so.

  2. Open ep101d01.sas from the demos folder.

  3. Find the section labeled Section 1: Access Data. In the PROC IMPORT step, replace FILEPATH as follows:
    • SAS Studio: Replace FILEPATH with the path to your EPG1V2/data folder.
    • Enterprise Guide: Replace FILEPATH with &path.

  4. Highlight the code in Section 1. Press F3 to run the selected code and examine the Output Data tab to view the imported table.

    The SAS code in this section does the following:
    • sets system options 
    • establishes the location of the course files and generated results
    • connects to the Excel Storm.xlsx data so that it can be used in the program
    • creates a temporary copy of the Storm_Damage Excel spreadsheet as a SAS table

  5. Click the Code or Program tab. Highlight the code in Section 2 and press F3 to run the selected code. Examine the Results tab to view the reports.

    The SAS code in this section does the following:
    • creates a frequency report to examine the unique values of the Basin and Type columns
    • calculates summary statistics for the MaxWindMPH and MinPressure columns
    • prints the first five rows from the storm_damage table that was imported from Excel

  6. Click the Code or Program tab. Highlight the code in Section 3 and press F3 to run the selected code. Examine the Output Data tab to view the generated tables.

    The SAS code in this section does the following:
    • adds additional storm data from 2017
    • cleans data by correcting case differences and assigning descriptive values to coded values
    • creates additional new columns with numeric calculations and character manipulations
    • joins tables to combine columns from two tables

  7. Click the Code or Program tab. Highlight the code in Section 4 and press F3 to run the selected code. Examine the Results tab to view the reports.

    The SAS code in this section does the following:
    • designates values to subset the data for the report as 2016 and NA (North Atlantic basin)
    • generates default reports as well as an Excel workbook with the reports
    • creates a frequency report for BasinName for the selected year
    • creates a summary statistics report and table that include statistics for storms in the selected year
    • creates a map of storms for the selected year and basin

  8. Open the Storm_Report2016.xlsx file and view the results that were created in Excel.
    • SAS Studio: In the Files and Folders panel, expand EPG1V2 and then data. Select the Storm_Report2016.xlsx file. Click Download and open the file when you are prompted in your browser.
    • Enterprise Guide: Click the Results - Excel tab and click Download.

Lesson 01


SAS® Programming 1: Essentials
Lesson 01, Section 2 Demo: Programming with SAS Studio


  1. Open SAS Studio.

  2. In the navigation pane on the left, select Libraries. Expand My Libraries and then SASHELP. Double-click the CLASS table to open the data. Next to the data is a panel that summarized the columns and their attributes. You can click the left arrow to minimize this panel and see more of the data. The SASHELP.CLASS table has 19 rows, each representing a different student, their name, sex, age, height, and weight. We need to write a program to take a look at this data. Close the SASHELP.CLASS tab.

  3. When SAS Studio opens, an empty Program window opens by default. If you do not have a Program window open, select New > SAS Program or press F4. Type or copy and paste the following program in the Code tab.
    data myclass;
        set sashelp.class;
    run;
    
    proc print data=myclass;
    run;
    This code reads the SASHELP.CLASS table, creates a copy called myclass, and prints the MYCLASS table. Click Run or press F3 to run the code.

  4. Select the Log tab. The log includes the program and messages returned from SAS. You can expand the Errors, Warnings, or Notes sections to see all messages in a summary list. You can click on any of the messages to find the corresponding message in the log. Fortunately our program ran just fine, so we just have notes.

  5. Click the Output Data and Results tabs to examine the report and the output data.

  6. Return to the Code tab. Highlight the PROC PRINT and RUN statements and click Run or press F3 to run just the selected text.

  7. Confirm that the log and results were replaced. The Results tab shows the report that was created from the PROC PRINT code. The output data does not display, because you did not run the section of the code that created the output data.

  8. To view multiple tabs at the same time, click one of the tabs (Code, Log, Output Data, or Results) and drag it to the side or bottom of the work area until a highlighted region appears. To return to a single window, drag the separated tab back to the main tab area.

SAS® Programming 1: Essentials
Lesson 01, Section 2 Demo: Programming with SAS Enterprise Guide


  1. Open SAS Enterprise Guide.

  2. In the Welcome window, select New Project. In Enterprise Guide, your work is organized in projects. As you open tables and programs or create new programs, shortcuts are added in your project in the Project Tree window.

  3. In the the lower left corner of the Servers window , expand Servers > Local > Libraries > SASHELP.
    Note: The Sashelp library is a collection of sample data files provided by SAS that are useful for testing and practicing. This course references various data files in Sashelp to illustrate programming syntax.

  4. Double-click the class table to open and view the data. The class data includes 19 students with their name, sex, age, height, and weight. 

  5. Select File > New > Program, or click New on the toolbar and select Program.

  6. Type or copy and paste the following program on the Program tab.
    Open code or syntax in a separate window.
    data myclass;
        set sashelp.class;
    run;
    
    proc print data=myclass;
    run;

  7. Click Run or press F3 to run the program. After the program runs, notice that multiple tabs are created.

  8. Click the Log tab. The log includes the program code and messages that are returned from SAS. The Log Summary is displayed by default at the bottom of the window. You can click on any of the messages in the Log Summary to find the message in the log. Note: If the Log Summary is closed, click Log Summary on the toolbar.

  9. Click the Output Data and Results tabs to examine the output. Output Data displays for the new table we created called myclass, and the Results tab displays the report.

  10. Return to the Program tab. Highlight the PROC PRINT and RUN statements and click the drop-down arrow next to Run and select Run Selection, or press F3.

  11. Click Yes when you are prompted to replace the results. Confirm that the log and the results were replaced.

  12. To view two tabs at the same time, click the Workspace Layout button on the toolbar and select either Stacked or Side By Side. You can select different tabs in each section of the layout. Close one of the sections when you are finished.

    Note: If you have more than one program open in Enterprise Guide, you can select the program to view in the drop-down list at the top of each section.

SAS® Programming 1: Essentials
Lesson 01, Section 3 Demo: Understanding SAS Program Syntax


  1. Open the p101d02.sas program from the demos folder. Run the program. Does it run successfully?

  2. Use the Format Code feature to improve the program spacing.
    • Enterprise Guide: Select Edit > Format Code. You can also right-click in the program and select Format Code or press Ctrl and I.
    • SAS Studio: Click the Format Code button. You can also right-click in the program and select Format Code.

  3. Add the following text as a comment before the DATA statement: Program created by < your-name >
  4. Note: Select the comment text and press Ctrl and / to surround it with /* and */.

  5. Comment out the first TITLE statement and the WHERE statement in PROC PRINT. Run the code and verify that 428 rows are included in the results.
  6. /*Program created by */
    data mycars;
        set sashelp.cars;
        AvgMPG=mean(mpg_city, mpg_highway);
    run;
    
    *title "Cars with Average MPG Over 35";
    
    proc print data=mycars;
        var make model type avgmpg;
        *where AvgMPG > 35;
    run;
    
    title "Average MPG by Car Type";
    
    proc means data=mycars 
         mean min max maxdec=1;
         var avgmpg;
         class type;
    run;
    
    title;
    

SAS® Programming 1: Essentials
Lesson 01, Section 3 Demo: Finding and Resolving Syntax Errors


  1. Open the p101d03.sas program from the demos folder. Identify the three syntax errors but do not fix them. Run the program.

  2. Carefully review the messages in the log. You can use the Log Summary to quickly locate the notes, warnings, and errors.

  3. Fix the code and rerun the program.
  4. data mycars;
        set sashelp.cars;
        AvgMPG=mean(mpg_city, mpg_highway);
    run;
    
    title "Cars with Average MPG Over 35";
    proc print data=mycars;
        var make model type avgmpg;
        where AvgMPG > 35;
    run;
    
    title "Average MPG by Car Type";
    proc means data=mycars mean min max maxdec=1;
        var avgmpg;
        class type;
    run;
    
    title;    

Lesson 02


SAS® Programming 1: Essentials
Lesson 02, Section 2 Demo: Exploring Automatic SAS Libraries


We recommend that you view this demo rather than perform the steps in your software. If you are using SAS Enterprise Guide to take this course, the libraries you define all point to the same location as the Work library, so you will not see the differences shown in this demo.


SAS® Programming 1: Essentials
Lesson 02, Section 2 Demo: Using a Library to Read Excel Files


  1. Open the Storm.xlsx file in Excel to view the data. Notice that, in the Storm_Summary worksheet, there are spaces in the Hem NS and Hem EW column headings. Close the Excel file after you finish viewing it. Note: The file must be closed before you assign a library to the file.

  2. Open p102d02.sas from the demos folder and find the Demo section.

  3. Complete the OPTIONS statement to ensure that column names follow SAS naming conventions.
    options validvarname=v7;
  4. Complete the LIBNAME statement to define a library named xlstorm that connects to the Storm.xlsx workbook.
    • SAS Studio: Replace FILEPATH with the path to your EPG1V2/data folder.
    • Enterprise Guide: Replace FILEPATH with &path.
    libname xlstorm xlsx "FILEPATH/storm.xlsx"; 
  5. Highlight the OPTIONS and LIBNAME statements and run the selected code. Use the navigation pane to find the xlstorm library. Open the storm_summary table. Notice that the Hem_NS and Hem_EW columns include underscores. Close the storm_summary table.

  6. Modify the PROC CONTENTS statement to read the storm_summary table in the xlstorm library.
    proc contents data=xlstorm.storm_summary;
    run;
  7. Add a statement to clear the xlstorm library. Highlight the entire demo program and run the selected code.
    libname xlstorm clear;
    Note:  In SAS Studio, if you do not submit the VALIDVARNAME=V7 option with the PROC CONTENTS step, the wrapper code by default resets the value of the VALIDVARNAME= option to ANY. This results in spaces in the Hem EW and Hem NS columns when the storm_summary table is read. To ensure that the VALIDVARNAME option remains set as V7, select More application options > Preferences and change the value of SAS variable name policy to V7. In Enterprise Guide, if you change the value of VALIDVARNAME with an OPTIONS statement, the wrapper code does not reset the option.

SAS® Programming 1: Essentials
Lesson 02, Section 3 Demo: Importing a Comma-Delimited (CSV) file


The storm_damage.csv file is in the data folder. Column names are in the first row, the data is comma-delimited, and there is a Date column. Data values that include commas are enclosed in quotation marks.

  1. Open the p102d03.sas program in the demos folder and find the Demo section.

  2. Complete the PROC IMPORT step to read storm_damage.csv and create a temporary SAS table named storm_damage_import. Replace the table if it exists.
    • SAS Studio: Replace FILEPATH with the path to your EPG1V2/data folder.
    • Enterprise Guide: Replace FILEPATH with &path.
    proc import datafile="FILEPATH/storm_damage.csv" dbms=csv
                out=storm_damage_import replace;
    run;
  3. Complete the PROC CONTENTS step to examine the properties of storm_damage_import.
    proc contents data=storm_damage_import;
    run; 
  4. Highlight the demo program and submit the selected code.


Lesson 03


SAS® Programming 1: Essentials
Lesson 03, Section 1 Demo: Exploring Data with SAS Procedures


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

Note: If you did not create the libname.sas program, complete the Activity: Create a Library for This Course (REQUIRED) in Lesson 2.

  1. Open p103d01.sas from the demos folder and find the Demo section of the program.
    • Complete the PROC PRINT statement to list the data in pg1.storm_summary.
    • Print the first 10 observations.
    • Highlight the step and run the selected code.

    proc print data=pg1.storm_summary (obs=10);
    run;   
        
  2. Add a VAR statement to include only the following columns: Season, Name, Basin, MaxWindMPH, MinPressure, StartDate, and EndDate.

  3. Enterprise Guide:
    To easily add column names, use the autocomplete prompts to view and select columns. You can either double-click on a column to add it in the program, or start to type the column name and press the spacebar when the correct column is highlighted.

    SAS Studio: To easily add column names, place your cursor after the keyword VAR. Use the Library section of the navigation pane to find the pg1 library. Expand the storm_summary table to see a list of column names. Hold down the Ctrl key and select the columns in the order in which you want them to appear in the statement. Drag the selected columns to the VAR statement.

    proc print data=pg1.storm_summary(obs=10);
        var Season Name Basin MaxWindMPH MinPressure StartDate
            EndDate;
    run;
  4. Add list first 10 rows as a comment before the PROC PRINT statement. Highlight the step and run the selected code.

  5. /*list first 10 rows*/
    proc print data=pg1.storm_summary(obs=10);
        var Season Name Basin MaxWindMPH MinPressure StartDate
            EndDate;
    run;
      
  6. Copy the PROC PRINT step and paste it at the end of the program.
    • Change PRINT to MEANS.
    • Remove the OBS= data set option to analyze all observations.
    • Modify the VAR statement to calculate summary statistics for MaxWindMPH and MinPressure.
    • Add calculate summary statistics as a comment before the PROC MEANS statement.
    • Highlight the step and run the selected code.

    /*calculate summary statistics*/
    proc means data=pg1.storm_summary;
        var MaxWindMPH MinPressure;
    run;    
  7. Copy the PROC MEANS step and paste it at the end of the program.
    • Change MEANS to UNIVARIATE.
    • Add examine extreme values as a comment before the PROC UNIVARIATE statement.
    • Highlight the step and run the selected code.

    /*examine extreme values*/
    proc univariate data=pg1.storm_summary;
        var MaxWindMPH MinPressure;
    run; 
      
  8. Copy the PROC UNIVARIATE step and paste it at the end of the program.
    • Change UNIVARIATE to FREQ.
    • Change the VAR statement to a TABLES statement to produce frequency tables for Basin, Type, and Season.
    • Add list unique values and frequencies as a comment before the PROC FREQ statement.
    • Highlight the step and run the selected code.

    /*list unique values and frequencies*/
    proc freq data=pg1.storm_summary;
        tables Basin Type Season;
    run; 

SAS® Programming 1: Essentials
Lesson 03, Section 2 Demo: Filtering Rows with Basic Operators


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

  1. Open p103d02.sas from the demos folder and find the Demo section of the program. Write a PROC PRINT step to list the data in pg1.storm_summary.

  2. Write a WHERE statement to include rows with MaxWindMPH values greater than or equal to 156 (Category 5 storms). Highlight the PROC PRINT step and run the selected code.
  3. proc print data=pg1.storm_summary;
        where MaxWindMPH >= 156;
    run;
  4. Modify the WHERE statement for each of the conditions below. Highlight the PROC PRINT step and run the selected code after each condition.
    • Basin equal to WP (West Pacific)
    • where Basin = "WP";      
    • Basin equal to SI or NI (South Indian or North Indian)
    • where Basin in ("SI" "NI");     
    • StartDate on or after January 1, 2010
    • where StartDate >= "01jan2010"d;
    • Type equal to TS (tropical storm) and Hem_EW equal to W (west)
    • where Type = "TS" and Hem_EW = "W"; 
    • MaxWindMPH greater than 156 or MinPressure less than 920
    • where MaxWindMPH > 156 or MinPressure < 920;
  5. In the final WHERE statement, are missing values included for MinPressure? How can you exclude missing values?
  6. where MaxWindMPH>156 or 0<MinPressure<920;    

SAS® Programming 1: Essentials
Lesson 03, Section 2 Demo: Filtering Rows Using Macro Variables


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

  1. Open p103d03.sas from the demos folder and find the Demo section of the program. Highlight the demo program and run the selected code.

  2. Write three %LET statements to create macro variables named WindSpeed, BasinCode, and Date. Set the initial values of the variables to match the WHERE statement.
    %let WindSpeed=156;
    %let BasinCode=NA;
    %let Date=01JAN2000;
  3. Modify the WHERE statements to reference the macro variables. Highlight the demo program and run the selected code. Verify that the same results are produced.
  4. proc print data=pg1.storm_summary;
        where MaxWindMPH>=&WindSpeed and Basin="&BasinCode" and
              StartDate>="&Date"d;
        var Basin Name StartDate EndDate MaxWindMPH;
    run;  
    
    proc means data=pg1.storm_summary;
        where MaxWindMPH>=&WindSpeed and Basin="&BasinCode" and
              StartDate>="&Date"d;
        var MaxWindMPH MinPressure;
    run; 
    Obs Basin Name StartDate EndDate MaxWindMPH
    1946 NA ISABEL 06SEP2003 20SEP2003 167
    2024 NA IVAN 02SEP2004 24SEP2004 167
    2086 NA EMILY 11JUL2005 21JUL2005 161
    2113 NA KATRINA 23AUG2005 31AUG2005 173
    2144 NA RITA 18SEP2005 26SEP2005 178
    2164 NA WILMA 15OCT2005 26OCT2005 184
    2262 NA DEAN 13AUG2007 23AUG2007 173
    2269 NA FELIX 31AUG2007 06SEP2007 173

    The MEANS Procedure
    Variable N Mean Std Dev Minimum Maximum
    MaxWindMPH 8 172.0000000 7.1113591 161.0000000 184.0000000
    MinPressure 8 908.3750000 16.1416719 882.0000000 929.0000000

  5. Change the values of the macro variables to values that you select. Possible values for Basin include NA, WP, SP, WP, NI, and SI. Highlight the demo program and run the selected code.

SAS® Programming 1: Essentials
Lesson 03, Section 3 Demo: Formatting Data Values in Results


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

  1. Open p103d04.sas from the demos folder and find the Demo section of the program. Write a PROC PRINT step to list the data in pg1.storm_damage. Highlight the step and run the selected code.

  2. Add a FORMAT statement to apply the MMDDYY10. format to Date, DOLLAR16. to Cost, and COMMA5. to Deaths. Highlight the step and run the selected code.
  3. proc print data=pg1.storm_damage;
        format Date mmddyy10. Cost dollar16. Deaths comma5.;
    run;   
  4. Change the width of MMDDYY to 8 and DOLLAR to 14. Highlight the step and run the selected code.

  5. Change MMDDYY to 6 and DOLLAR to 10. Highlight the step and run the selected code again. What happens to the formatted values?

SAS® Programming 1: Essentials
Lesson 03, Section 4 Demo: Identifying and Removing Duplicate Values


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

  1. Open p103d05.sas from the demos folder and find the Demo section of the program.
    • Modify the first PROC SORT step to sort by all columns and remove any duplicate rows.
    • Write the removed rows to a table named storm_dups.
    • Highlight the step and run the selected code.
    • Confirm that there are 107,821 rows in storm_clean and 214 rows in storm_dups.
    proc sort data=pg1.storm_detail out=storm_clean
              noduprecs dupout=storm_dups;
       by _all_;
    run; 
  2. Run the second PROC SORT step and confirm that the first row for each storm represents the minimum value of Pressure.

    Note: Because storm names can be reused in multiple years and basins, unique storms are grouped by sorting by Season, Basin, and Name

  3. Modify the third PROC SORT step to sort the min_pressure table and keep the first row for each storm. You do not need to keep the removed duplicates. Highlight the step and run the selected code.
  4. proc sort data=min_pressure nodupkey;
        by descending Season Basin Name;
    run;

Lesson 04


SAS® Programming 1: Essentials
Lesson 04, Section 1 Demo: Working with the DATA Step


  1. Open a new program window and type the following code:
  2. data myclass;
        set sashelp.class;
    run;
  3. Add a WHERE statement to select only rows where Age is greater than or equal to 15. Run the code and view the results.
  4. data myclass;
        set sashelp.class;
        where age >=15;
    run;
  5. Add a KEEP statement to keep only the Name, Age, and Height columns. Run the code and view the results.
  6. data myclass;
        set sashelp.class;
        where age >=15;
        keep Name Age Height;
    run:
    
  7. Comment out the KEEP statement and add a DROP statement to drop Sex and Weight. Run the code and view the results. Notice you have the same 3 columns in the data.
  8. data myclass;
        set sashelp.class;
        where age >=15;
        /*keep Name Age Height;*/
        drop Sex Weight;
    run;
    
  9. Delete or comment out the DROP and KEEP statements. Add a FORMAT statement to format the values of Height rounded to the nearest tenth, and the values of Weight to the nearest whole number. Run the code and view the results. The formats are applied to the columns as permanent attributes.
  10. data myclass;
        set sashelp.class;
        where age >=15;
        format height 4.1 Weight 3.;
    run;

SAS® Programming 1: Essentials
Lesson 04, Section 2 Demo: Using Expressions to Create New Columns


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

  1. Open p104d02.sas from the demos folder and find the Demo section of the program. Add an assignment statement to create a numeric column named MaxWindKM by multiplying MaxWindMPH by 1.60934.

  2. Add a FORMAT statement to round MaxWindKM to the nearest whole number.

  3. Add an assignment statement to create a new character column named StormType that is equal to Tropical Storm. Highlight the DATA step and run the selected code.
  4. data tropical_storm;
        set pg1.storm_summary;
        drop Hem_EW Hem_NS Lat Lon;
        where Type="TS";
        MaxWindKM=MaxWindMPH*1.60934;
        format MaxWindKM 3.;
        StormType="Tropical Storm";
    run;   

SAS® Programming 1: Essentials
Lesson 04, Section 2 Demo: Using Character Functions


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

  1. Open p104d03.sas from the demos folder and find the Demo section of the program. Add an assignment statement to convert Basin to all uppercase letters using the UPCASE function.

  2. Add an assignment statement to convert Name to proper case using the PROPCASE function.

  3. Add an assignment statement to create Hemisphere, which concatenates Hem_NS and Hem_EW using the CATS function.

  4. Add an assignment statement to create Ocean, which extracts the second letter of Basin using the SUBSTR function. Highlight the DATA step and run the selected code.
  5. data storm_new;
        set pg1.storm_summary;
        drop Type Hem_EW Hem_NS MinPressure Lat Lon;
        Basin=upcase(Basin);
        Name=propcase(Name);
        Hemisphere=cats(Hem_NS, Hem_EW);
        Ocean=substr(Basin,2,1);
    run;   

SAS® Programming 1: Essentials
Lesson 04, Section 2 Demo: Using Date Functions


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

  1. Open p104d04.sas from the demos folder and find the Demo section of the program. Create the column YearsPassed and use the YRDIF function. The difference in years should be based on each Date value and today's date.

  2. Create Anniversary as the day and month of each storm in the current year.

  3. Format YearsPassed to round the value to one decimal place, and Date and Anniversary as MM/DD/YYYY. Highlight the DATA step and run the selected code.
  4. data storm_damage2;
        set pg1.storm_damage;
        drop Summary;
        YearsPassed=yrdif(Date,today(),'age');
        Anniversary=mdy(month(Date),day(Date),year(today()));
        format YearsPassed 4.1 Date Anniversary mmddyy10.; 
    run; 

SAS® Programming 1: Essentials
Lesson 04, Section 3 Demo: Conditional Processing with IF-THEN


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

  1. Open p104d05.sas from the demos folder and find the Demo section of the program. Create a column named PressureGroup that is based on the following assignments:
    • MinPressure<=920 ⇒ 1
    • MinPressure>920 ⇒ 0
    data storm_new;
        set pg1.storm_summary;
        keep Season Name Basin MinPressure PressureGroup;
        if MinPressure<=920 then PressureGroup=1;
        if MinPressure>920 then PressureGroup=0;
    run;
  2. Highlight the DATA step, run the selected code, and examine the data. What value is assigned to PressureGroup when MinPressure is missing?

  3. Add a new IF-THEN statement before the existing IF-THEN statements to assign PressureGroup=. if MinPressure is missing.
  4. data storm_new;
        set pg1.storm_summary;
        keep Season Name Basin MinPressure PressureGroup;
        if MinPressure=. then PressureGroup=.;
        if MinPressure<=920 then PressureGroup=1;
        if MinPressure>920 then PressureGroup=0;
    run; 
  5. Highlight the DATA step and run the selected code. What value is assigned to PressureGroup?

    When MinPressure is missing, the first two IF conditions are true. The last assignment statement determines the value of PressureGroup.


SAS® Programming 1: Essentials
Lesson 04, Section 3 Demo: Processing Multiple Statements with IF-THEN/DO


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

  1. Open p104d07.sas from the demos folder and find the Demo section of the program. Modify the IF-THEN statements to use IF-THEN/DO syntax to write rows to either the indian, atlantic, or pacific table based on the value of Ocean. Highlight the DATA step and run the selected code.
  2. data indian atlantic pacific;
        set pg1.storm_summary;
        length Ocean $ 8;
        keep Basin Season Name MaxWindMPH Ocean;
        Basin=upcase(Basin);
        OceanCode=substr(Basin,2,1);
        if OceanCode="I" then do;
           Ocean="Indian";
           output indian;
        end;
        else if OceanCode="A" then do;
           Ocean="Atlantic"; 
           output atlantic;
        end;
        else do;
           Ocean="Pacific";
           output pacific;
        end;
    run;

Lesson 05


SAS® Programming 1: Essentials
Lesson 05, Section 1 Demo: Enhancing Reports


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

  1. Open p105d01.sas from the demos folder and find the Demo section of the program.
    • Add a PROC SORT step before PROC PRINT to sort pg1.storm_final by BasinName and descending MaxWindMPH.
    • Create a temporary table named storm_sort.
    • Filter the rows to include only MaxWindMPH>156.
    proc sort data=pg1.storm_final out=storm_sort;
        by BasinName descending MaxWindMPH;
        where MaxWindMPH > 156;
    run;
  2. Modify the PROC PRINT step to read the storm_sort table and group the report by BasinName.

  3. Add the following title: Category 5 Storms. Clear the title for future results.

  4. Add labels for the following columns and ensure that PROC PRINT displays the labels:
    • MaxWindMPH > Max Wind (MPH)
    • MinPressure > Min Pressure
    • StartDate > Start Date
    • StormLength > Length of Storm (days)

  5. Add the NOOBS option in the PROC PRINT statement to suppress the OBS column. Highlight the demo program and run the selected code.
  6. title "Category 5 Storms";
    proc print data=storm_sort label noobs;
        by BasinName;
        var Season Name MaxWindMPH MinPressure StartDate StormLength;
        label MaxWindMPH="Max Wind (MPH)"
              MinPressure="Min Pressure"
              StartDate="Start Date"
              StormLength="Length of Storm (days)";
    run;
    title;
    

SAS® Programming 1: Essentials
Lesson 05, Section 2 Demo: Creating Frequency Reports and Graphs


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

Note: Highlight the demo program and run the selected code after each step.

  1. Open p105d02.sas from the demos folder and find the Demo section of the program. Highlight the PROC FREQ step and run the selected code. Examine the default results.

  2. In the PROC FREQ statement, add the ORDER=FREQ option to sort results by descending frequency. Add the NLEVELS option to include a table with the number of distinct values.
  3. proc freq data=pg1.storm_final order=freq nlevels;
        tables BasinName Season;
    run; 
  4. Add the NOCUM option in the TABLES statement to suppress the cumulative columns.
  5. proc freq data=pg1.storm_final order=freq nlevels;
        tables BasinName Season / nocum;
    run; 
  6. Change Season to StartDate in the TABLES statement. Add a FORMAT statement to display StartDate as the month name (MONNAME.).
  7. proc freq data=pg1.storm_final order=freq nlevels;
        tables BasinName StartDate / nocum;
        format StartDate monname.;
    run;
  8. Add the ODS GRAPHICS ON statement before PROC FREQ. Use the PLOTS=FREQPLOT option in the TABLES statement to create a bar chart. Add the chart options ORIENT=HORIZONTAL and SCALE=PERCENT.
  9. ods graphics on;
    proc freq data=pg1.storm_final order=freq nlevels;
        tables BasinName StartDate /
               nocum plots=freqplot(orient=horizontal scale=percent);
        format StartDate monname.;
    run; 
  10. Add the title Frequency Report for Basin and Storm Month. Turn off the procedure title with the ODS NOPROCTITLE statement. Add a LABEL statement to display BasinName as Basin and StartDate as Storm Month. Clear the titles and turn the procedure titles back on.
  11. ods graphics on;
    ods noproctitle;
    title "Frequency Report for Basin and Storm Month";
    proc freq data=pg1.storm_final order=freq nlevels;
        tables BasinName StartDate / 
               nocum plots=freqplot(orient=horizontal scale=percent);
        format StartDate monname.;
        label BasinName="Basin"
              StartDate="Storm Month";
    run;
    title;
    ods proctitle;  

SAS® Programming 1: Essentials
Lesson 05, Section 2 Demo: Creating Two-Way Frequency Reports


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

Note: Highlight the PROC FREQ step and run the selected code after each step.

  1. Open p105d03.sas from the demos folder and find the Demo section of the program. Highlight the PROC FREQ step, run the selected code, and examine the default results.

  2. Add the NOPERCENT, NOROW, and NOCOL options in the TABLES statement.
  3. tables StartDate*BasinName / norow nocol nopercent
  4. Delete the options in the TABLES statement and add the CROSSLIST option.
  5. tables StartDate*BasinName / crosslist;
    
  6. Change the CROSSLIST option to the LIST option in the TABLES statement.
  7. tables StartDate*BasinName / list;
  8. Delete the previous options and add OUT=STORMCOUNTS. Add NOPRINT to the PROC FREQ statement to suppress the report.
  9. proc freq data=pg1.storm_final noprint;
        tables StartDate*BasinName / out=stormcounts;
        format StartDate monname.;
        label BasinName="Basin"
              StartDate="Storm Month";
    run;

SAS® Programming 1: Essentials
Lesson 05, Section 3 Demo: Creating Summary Statistics Reports


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

Note: Highlight the PROC MEANS step and run the selected code after each step.

  1. Open p105d04.sas from the demos folder and find the Demo section of the program. Run the step and examine the starting report.

  2. List the following statistics in the PROC MEANS statement: MEAN, MEDIAN, MIN, and MAX. Add the MAXDEC=0 option to round statistics to the nearest integer.

  3. proc means data=pg1.storm_final mean median min max maxdec=0;
        var MaxWindMPH;
    run;   
        
  4. The CLASS statement can be used to calculate statistics for groups. Add a CLASS statement and list the BasinName column.
  5. Note: The CLASS statement does not require the data to be sorted.

    proc means data=pg1.storm_final mean median min max maxdec=0;
        var MaxWindMPH;
        class BasinName;
    run;   
        
  6. Add StormType as an additional column in the CLASS statement. Run the program and notice that one report is created with statistics that are calculated for the combination of BasinName and StormType values.

  7. proc means data=pg1.storm_final mean median min max maxdec=0;
        var MaxWindMPH;
        class BasinName StormType;
    run;   
        
  8. The WAYS statement can be used to indicate the combinations of class columns to use for creating the report. Add the WAYS statement and provide a value of 1.

  9. proc means data=pg1.storm_final mean median min max maxdec=0;
        var MaxWindMPH;
        class BasinName StormType;
        ways 1;
    run;
      
  10. Change the WAYS statement to list 0, 1, and 2.

  11. proc means data=pg1.storm_final mean median min max maxdec=0;
        var MaxWindMPH;
        class BasinName StormType;
        ways 0 1 2;
    run;

Lesson 06


SAS® Programming 1: Essentials
Lesson 06, Section 1 Demo: Exporting Data to an Excel Workbook


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

Note: If you did not define the outpath macro variable, run the libname.sas program that was created in Activity: Create a Macro Variable (REQUIRED).

  1. Open p106d01.sas from the demos folder and find the Demo section of the program. Examine the DATA and PROC MEANS steps and identify the temporary SAS tables that will be created. Highlight the demo program and run the selected code.

  2. Add a LIBNAME statement to create a library named xlout that points to an Excel file named southpacific.xlsx.
    Note:
    Use &outpath to provide the path to the file.
  3. libname xlout xlsx "&outpath/southpacific.xlsx";
  4. Modify the DATA and PROC steps to write output tables to the xlout library.
  5. libname xlout xlsx "&outpath/southpacific.xlsx";
    data xlout.South_Pacific;
        set pg1.storm_final;
        where Basin="SP";
    run;
    
    proc means data=pg1.storm_final noprint maxdec=1;
        where Basin="SP";
        var MaxWindKM;
        class Season;
        ways 1;
        output out=xlout.Season_Stats n=Count
               mean=AvgMaxWindKM max=StrongestWindKM;
    run; 
  6. Add a LIBNAME statement to clear the xlout libref. Highlight the demo program and run the selected code.
  7. libname xlout clear; 
  8. Open the southpacific.xlsx workbook and confirm that the data is contained in the worksheets that are named South_Pacific and Season_Stats.
    • SAS Studio: In the Files and Folders panel, navigate to EPG1V2 > output. Select southpacific.xlsx, and click Download.
    • SAS Enterprise Guide: You can only view this file if you set outpath to a folder where you can write files. Select Open > Other and navigate to the location you specified when you defined &outpath. Select southpacific.xlsx and click Open.

SAS® Programming 1: Essentials
Lesson 06, Section 2 Demo: Exporting Results to Excel


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

  1. Open p106d02.sas from the demos folder and find the Demo section in the program.
    • Add an ODS statement to create an Excel file named wind.xlsx. Use &outpath to provide the path to the file. 
    • Close the Excel destination at the end of the program.
    • Highlight the demo program and run the selected code.

      Note: If you are using Enterprise Guide 8.1 or later, you receive a warning in the log. By default, it uses the graph format Default. This allows the Output Delivery System (ODS) to decide on the best graph format. To adjust the default settings, go to Tools > Results > Graphs and change the graph format. You can also use the statement GOPTIONS DEV=PNG before the ODS statement.

    ods excel file="&outpath/wind.xlsx";
    title "Wind Statistics by Basin";
    ...
    title;
    ods proctitle;
    ods excel close;
  2. Open the Excel file.
    • SAS Studio: In the Files and Folders panel, navigate to EPG1V2 > output, select wind.xlsx and click Download.
    • Enterprise Guide: Click Results and select the Excel file. Right-click and select Open.

  3. Examine the Excel workbook. Notice the light blue background in the results that are generated by the default style. Also notice the default spreadsheet names. Close the Excel file.

  4. Examine the available style options by submitting the following program:
  5. proc template;
        list styles;
    run;
  6. In the first ODS EXCEL statement, change the style by adding the STYLE=SASDOCPRINTER option.Use the SHEET_NAME= option to name the first worksheet Wind Stats.

    ods excel file="&outpath/wind.xlsx" style=sasdocprinter
              options(sheet_name='Wind Stats');
    title "Wind Statistics by Basin";
    ods noproctitle;
    proc means data=pg1.storm_final min mean median max maxdec=0;
        class BasinName;
        var MaxWindMPH;
    run;
    
    title "Distribution of Maximum Wind";
    proc sgplot data=pg1.storm_final;
        histogram MaxWindMPH;
        density MaxWindMPH;
    run;
    title;
    ods proctitle;
    ods excel close; 
  7. Add another ODS EXCEL statement with the SHEET_NAME= option before the second TITLE statement and the PROC SGPLOT step. Name the second worksheet Wind Distribution. Highlight the demo program and run the selected code. Open the Excel file to view the results.
  8. ods excel file="&outpath/wind.xlsx" style=sasdocprinter
              options(sheet_name='Wind Stats');
    title "Wind Statistics by Basin";
    ods noproctitle;
    proc means data=pg1.storm_final min mean median max maxdec=0;
        class BasinName;
        var MaxWindMPH;
    run;
    
    ods excel options(sheet_name='Wind Distribution');
    title "Distribution of Maximum Wind";
    proc sgplot data=pg1.storm_final;
        histogram MaxWindMPH;
        density MaxWindMPH;
    run;
    title;
    ods proctitle;
    ods excel close; 

SAS® Programming 1: Essentials
Lesson 06, Section 2 Demo: Exporting Results to PDF


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

  1. Open p106d03.sas from the demos folder and find the Demo section of the program. Run the program and open the PDF file to examine the results. Notice that bookmarks are created, and they are linked to each procedure's output.

  2. Add the STARTPAGE=NO option to eliminate page breaks between procedures. Add the STYLE=JOURNAL option.
  3. ods pdf file="&outpath/wind.pdf"  startpage=no style=journal; 
  4. To customize the PDF bookmarks, add the PDFTOC=1 option to ensure that bookmarks are expanded only one level when the PDF is opened. To customize the bookmark labels, add the ODS PROCLABEL statement before each PROC with custom text.
  5. ods pdf file="&outpath/wind.pdf" startpage=no style=journal
             pdftoc=1; 
    ods noproctitle;
    
    ods proclabel "Wind Statistics";
    title "Wind Statistics by Basin";
    proc means data=pg1.storm_final min mean median max maxdec=0;
        class BasinName;
        var MaxWindMPH;
    run;
    
    ods proclabel "Wind Distribution"; 
    title "Distribution of Maximum Wind";
    proc sgplot data=pg1.storm_final;
        histogram MaxWindMPH;
        density MaxWindMPH;
    run;
    title;
    
    ods proctitle;
    ods pdf close; 
  6. Run the program and open the PDF file.

Lesson 07


SAS® Programming 1: Essentials
Lesson 07, Section 1 Demo: Reading and Filtering Data with SQL


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

  1. Open p107d01.sas from the demos folder and find the Demo section of the program. Add a SELECT statement to retrieve all columns from pg1.storm_final. Highlight the step and run the selected code. Examine the log and results.
  2. proc sql;
    select *
        from pg1.storm_final;
    quit;   
  3. Modify the query to retrieve only the Season, Name, StartDate, and MaxWindMPH columns. Format StartDate with MMDDYY10. Highlight the step and run the selected code.
  4. proc sql;
    select Season, Name, StartDate format=mmddyy10., MaxWindMPH
        from pg1.storm_final;
    quit;    
  5. Modify Name in the SELECT clause to convert the values to proper case.
  6. proc sql;
    select Season, propcase(Name) as Name, 
           StartDate format=mmddyy10., MaxWindMPH 
        from pg1.storm_final;
    quit;
  7. Add a WHERE clause to include storms during or after the 2000 season with MaxWindMPH greater than 156.

  8. Add an ORDER BY clause to arrange rows by descending MaxWindMPH, and then by Name.

  9. Add TITLE statements to describe the report. Highlight the step and run the selected code.
  10. title "International Storms since 2000";
    title2 "Category 5 (Wind>156)";
    proc sql;
    select Season, propcase(Name) as Name, 
           StartDate format=mmddyy10., MaxWindMPH 
        from pg1.storm_final
        where MaxWindMPH > 156 and Season >= 2000
        order by MaxWindMPH desc, Name;
    quit;
    title;   

SAS® Programming 1: Essentials
Lesson 07, Section 2 Demo: Joining Tables with PROC SQL


Reminder: If you restarted your SAS session,you must recreate the PG1 library so you can access your practice files. In SAS Studio, open and submit the libname.sas program in the EPG1V2 folder. In Enterprise Guide, run the Autoexec process flow.

  1. Open pg1.storm_summary and pg1.storm_basincodes and compare the columns. Identify the matching column.

  2. Open the p107d02.sas program in the demos folder and find the Demo section of the program. Add pg1.storm_basincodes to the FROM clause to perform an inner join on Basin. Qualify the Basin columns as table-name.col-name in the ON expression only.

  3. Add the BasinName column to the query after Basin. Highlight the step, run the selected code, and examine the log. Why does the program fail?
  4. proc sql;
    select Season, Name, Basin, BasinName, MaxWindMPH
        from pg1.storm_summary inner join pg1.storm_basincodes
            on storm_summary.basin=storm_basincodes.basin
        order by Season desc, Name;
    quit;     
  5. Modify the query to qualify the Basin column in the SELECT clause. Highlight the step and run the selected code.
  6. proc sql;
    select Season, Name, storm_summary.Basin, BasinName, MaxWindMPH
        from pg1.storm_summary inner join pg1.storm_basincodes
            on storm_summary.basin=storm_basincodes.basin
        order by Season desc, Name;
    quit;