Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

STAT0023 Workshop 7: Introduction to SAS

Self-study materials

This week we will introduce you to the SAS system and show you how to carry out some basic     data manipulations and very simple plots. The main goal of the self-study notes is to get you set up for using SAS and explore some simple examples.

 

1      Setting up

For this self-study session, in addition to these instructions you will need the following, all of which can be downloaded from the “Week 7” tab of the Moodle page:

•      The lecture materials.

•      The SAS program GalapagosProg1.sas.

•      The data file galapagos.dat. This is the same file that you used in Workshops 1 and 6: if  you already have a copy in the same folder as GalapagosProg1.sas then you don’t need to download it again.

1.1    Starting SAS for the first time

Your first task in the self-study session is to get SAS up and running. It is recommended that you run SAS usingDesktop@UCL, but if you prefer it is also available for Windows users through the UCL Software Database(there are some instructions for doing this on the course Moodle page,   accessible from the Course overview and useful information tab).

Once you have connected toDesktop@UCL, click on “Desktop@UCLAnywhere”. This should    open a virtual Windows session. It can take a little while to load, so please be patient. To start   SAS on the UCL Desktop, click the Windows icon at the bottom left-hand corner of the screen, type SAS 9.4 in the search box there and then click on ‘SAS 9.4 (English)’ when it appears (NB not any of the other SAS-related programs!). You should see the following window:


 

 

The notification dialogue tells you about some recent changes to the default output format in   SAS, and also gives you a link to some “Getting Started” guides. You can explore these in your   own time if you like. For the moment, just click the Close button. You can now see three panes in your SAS window, as follows:

•      The Explorer pane: this allows you to see your SAS libraries, each of which is a collection of related data files — more on these below. On Windows systems, the Explorer pane        looks very much like the Windows Explorer that many of you will be familiar with. This is      potentially confusing: the SAS Explorer pane is just designed to help you navigate round  the SAS files on your computer. This will make more sense shortly.

•      The Editor pane: this is where we will type SAS programs. It is similar to the script pane in an RStudio session. It is only available in the Windows version of SAS, however.

•      The Log pane: this is where messages about your SAS session (including error messages etc.) will appear.

There is also a Results pane, hidden beneath the Explorer pane but accessible by clicking on a tab at the bottom left of your SAS window. We don’t need it yet.

1.2    Setting up a library

The notion of a library is important in SAS. As noted above, a library is a collection of related

files. When you start SAS for the first time, some default libraries are already available to you. To

see what these are, double-click the Libraries icon         in the Explorer pane. There are

several libraries here, of which the ones you need to know about are:


•      Sashelp: this library contains sample datasets that are useful for learning about the capabilities of SAS (similar to the iris data that we used when learning R).

•      Work: this library contains temporary datasets that are created for use solely during the    current session. When you quit SAS, the contents of the Work library are not saved. The   Work library plays a similar role to the workspace in R. The only difference is that R gives  you the option to save your workspace whenever you finish a session. In SAS you have to be a bit careful about this!

You don’t need to worry about the other default libraries. However, you should create a new library for all of your STAT0023 SAS work. To do this, proceed as follows:

1.     Click the ‘New Library’ button  on the ribbon at the top of the SAS window, as shown below:

 

2.     In the dialogue box that appears, enter a value for the library name (I suggest you call it      STAT0023: I will assume this throughout the rest of the course); ensure that the Enable at startup box is checked, and then click the Browse button to choose a location on your      computer to store the library files:


 

When choosing a location for your library files, I suggest you navigate to the STAT0023

folder that you created in the first workshop of the course and then create a subfolder of    this called SASWork or something. This will ensure that your SAS library files are stored in a location on your computer where you can find them; but they won’t interfere with any        other files that you produce during the course.

3.     When you have selected a location, click OK to create the library.

To check that your library has been created successfully and that it loads automatically every    time you start SAS, quit SAS (choose Exit from the File menu), then start it up again and       double-click the Libraries icon in the Explorer pane. You should see your STAT0023 library listed there now. If not, it means that you didn’t follow the above instructions properly — go     back and try again!

1.3    Setting the current folder

In addition to your STAT0023 SAS library, SAS needs to be able to find your programs and any   other ‘non-SAS’ files that you will need. The easiest way to ensure this is to Change the current folder in SAS-speak: this is exactly the same idea as setting the working directory in RStudio at  the start of each session. To do it, select Options on the Tools menu, then Change Current   Folder and use the resulting dialogue box to navigate to the place where you saved the files     that you downloaded from the Moodle page. You should do this whenever you start SAS in this course.

Now you’re ready to do some SAS.


2      A first SAS program

To get started, we’ll look at the Galapagos biodiversity data that you should be familiar with by now. At the start of this workshop you downloaded the file GalapagosProg1.sas: this is a        simple SAS program illustrating how to read data from an ASCII file, produce some simple         descriptive statistics and make some simple plots. Here are your instructions:

1.     On the File menu in SAS, click Open Program. You should see the GalapagosProg1.sas file listed (if not, make sure you saved the file in the right place, and that you set the            current folder correctly in Section 1.3). Double-click on the file name to open it. It will open in a new Editor pane.

2.     Without attempting to run the program, read through it so that you have an idea what it does. Notice the following:

–      In SAS, comments are indicated by /* ... */. Unlike R, you need to indicate both  the start and end of a comment: if you omit the */, SAS will interpret all subsequent lines as though they are comments!

–      All statements in the program end with a semicolon ";". This is very important — if there is no semicolon on a line, SAS will think that the next line is a continuation of the same statement.

–      The first statement defines a title that will appear on each page of the program

output. This is an example of a global statement: its purpose is to set values and    attributes for all the subsequent output. Here, setting a title can be helpful as a way of labelling the output, analogous to the use of cat() statements to produce          helpful headings etc. in R. As supplied to you, this program just uses the title            "First SAS program: Galapagos biodiversity data". Feel free to change it:  if you do this, you’ll need to save the program before running it (see Section 2.4      below).

–      The remainder of the program is divided into sections, each taking one of the following forms:

 

The DATA section is a SAS data step: it defines a SAS dataset to the system (in this   case by reading from the file called galapagos.dat, starting from the second line — the first line of the file contains variable names but SAS can’t recognise these). The    PROC sections are SAS procedures, which are used to produce reports and analyses. All SAS programs consist of combinations of DATA and PROC steps.

–      Unlike R, SAS code is not case-sensitive. Therefore DATA and data mean the same thing: the data step could equivalently have been written as


Although it doesn’t matter whether you use upper or lower case, you should try and find a consistent style and stick to it. In this course, I will use UPPER CASE LETTERS for all SAS commands so that it is easy to recognise them.

3.     When you have finished reading through the program, scroll back to the top. With the      mouse, highlight the first statement i.e. TITLE ... ;, and then click the ‘Run’ button  on the ribbon at the top of the SAS window as shown:

 

You will see the statement appear in the Log pane, but otherwise nothing will happen: the TITLE statement is just used for formatting the subsequent output.

4.     Highlight the statements for the next DATA step (i.e. the lines from DATA Galapagos; down to the first RUN; statement), and click the ‘Run’ button        again. This time, you will see        some information about the data file in the Log pane.1

5.     In the Explorer pane, double-click the Libraries icon  and then the Work icon. You will see that this contains an object called Galapagos. Congratulations — you have just       created your first SAS data set! Don’t get too complacent though, there is more to do.

6.     Go back to the GalapagosProg1.sas pane, scroll down a bit more, highlight the next two statements (PROC PRINT; and RUN;) and click the ‘Run’ button. This time, you get some    real output. The PRINT procedure lists the dataset: the results appear in the Results     Viewer pane. Notice the title at the top of the output, corresponding to the TITLE       statement that you entered previously.

7.     Click the GalapagosProg1.sas tab to go back to your program, and run the next two pairs of statements (PROC MEANS and PROC PLOT) in the same way. Make sure you understand     the results.

8.     Next, run the next two global statements (TITLE and SYMBOL1), and then the PROC GPLOT statements, which produce (allegedly) ‘high-resolution’ graphics. Notice that the PROC    GPLOT statements both have additional QUIT; statements after the usual RUN;. This is        because the procedures allow the user to add more detail to the plot by submitting           additional statements until a QUIT; statement is encountered.

You may wonder what is the role of the RUN; statements in the program. The answer is that the  previous steps are all stored, but not executed until a RUN; statement is given (a legacy of the     computer systems of the 1970s!). Strictly speaking therefore, you don’t need RUN; statements     throughout your program — you could just include a single one at the end. However, without      them you wouldn’t be able to ‘step through’ the program as you have just done, and to view the result of each step as you go.

Before you proceed, take a quick look at the contents of the Log pane. Hopefully, all of the text  in this window will be either black (for the statements that you entered) or blue (providing          information about what was done). The Log pane will also show any errors in your statements in red, and warnings in green. Hopefully there aren’t any at the moment. However, it is good          practice always to check the Log pane to ensure that your statements have executed properly.

2.1    SAS datasets

You have just been introduced to the main concepts involved in SAS programming. Before

moving on however, it is worth saying something about the structure of a SAS dataset — such as Galapagos in the example. All SAS datasets can be thought of as tables with rows and columns  and, as such, are analogous to data frames in R. There are some differences, however. The most  important ones are:

•      SAS has a much more restricted variety of data types than R: in SAS, variables are either ‘numeric’ or ‘character’ (no ‘factor’ or ‘logical’ variables, for example).

•      In R, the symbol NA is used to denote a missing value. In SAS, the missing value code is a blank " " for character variables but a period “.” for numeric variables.


•      SAS offers perhaps finer control over the way that variables are formatted for output. This is useful when producing reports in a business environment: perhaps one of your variables      represents sales revenue, in which case you might want to present its values to two decimal

places with a dollar sign in front: this can be done by associating the variable with a format

such as DOLLAR12.2 (there will be enough space for 12 digits, with two digits after the       decimal place). To see the formats available for SAS variables, you can use the help system (see Section 3 below).

2.2    Saving a SAS dataset

In the example above, the Galapagos dataset was stored in the Work library. As noted in Section 1.2, the contents of this library are not saved when you finish your SAS session. In this particular  case, it probably doesn’t matter too much: the data are already stored in a text file and it takes

almost no time to read them. For more substantial tasks however, you might want to save your    SAS datasets permanently for subsequent use. This is the purpose of your STAT0023 library from Section 1.2.

To save your dataset to the STAT0023 library, add the following lines to the end of your GalapagosProg1.sas script (take care with the semicolons!):

These statements can be interpreted as: define a new dataset called galapagos in the STAT0023 library, and take (‘set’) the values of all its variables from the existing temporary dataset called

Galapagos.

Check the lines that you have just typed, and then run them: you know how to do this. Check

the Log pane — if there were any errors, go back and correct them.2All being well, you should see a note in the Log pane saying that 30 observations were read from the dataset                   WORK.GALAPAGOS and that the dataset STAT0023.GALAPAGOS has 30 observations and 8          variables.

The code above needs some explanation, as follows:

•      Compare the DATA statement with the earlier DATA statement in the program, and notice that the latest one uses a two-part name STAT0023.galapagos whereas the earlier one used a one-part name (just Galapagos).

•      In a two-part name, the first part defines the library name (here STAT0023) and the second part defines the dataset name. A one-part name just defines the dataset name; the dataset is stored in the temporary Work library.

So the code above has the effect of copying the temporary Galapagos dataset into the              permanent STAT0023 library. To see this, go back to the Explorer pane and navigate to your    STAT0023 library (to get there, you may need to click the ‘Up One Level’ icon  on the              ribbon). You should now have a Galapagos dataset here as well. This will still be available to you the next time you use SAS.

An even easier way to ensure that a dataset is saved is to read it directly into the desired library. To do this in the example above, we could have used

2.3    Saving your results

As well as saving your dataset, you might want to save your results. SAS displays the results in the Results Viewer pane. If the Results Viewer pane is not visible, you can display it by    clicking on its tab at the bottom of the SAS window. Then, to save it as an HTML file, use click   Save As on the File menu.

The results are formatted into an HTML web page by default. This is great if you want your results in HTML format (e.g. to post as a web page) or if you have a magic piece of word processing         software that can import HTML files directly. Otherwise however, it isn’t very useful. Fortunately,    you can change this default behaviour. To do this: on the Tools menu, click Options and then    Preferences. In the resulting dialogue box, click the Results tab: uncheck the Create HTML   and Use ODS Graphics boxes,3 check the Create listing box and click OK. Now, if you run     some statements you will find that the ‘text-based’ results are displayed in the Output pane,

whereas graphics appear in separate panes. The contents of the Output pane can now be saved in a variety of file formats — including RTF (‘rich text format’) which can be imported into word   processing software such as Word.

In practice, you might make some mistakes while running a program, and you don’t want to        include the incorrect results in your saved copy. The easiest way to create a ‘clean’ copy is to       correct all the errors, clear any output panes completely (to do this, click somewhere in the pane that you want to clear and then click Clear All on the Edit menu) and then rerun the entire     program: this is done by placing the cursor anywhere within the GalapagosProg1.sas pane       (without highlighting anything) and clicking the ‘Run’ button.

If you have turned off the ODS graphics (see above), you can also save your graphs. You may       have your own views as to the desirability of this, when the quality from R is so much better (and easier). However, if you really want to use SAS graphics then you can right-click on the pane for  the graph that you want to save, then click File and Export as Image on the drop-down

menu that appears. You can then choose from several output file formats, from the Save as  type menu in the resulting dialogue box. This gives you a way of generating plots that can be included in reports and Powerpoint presentations.

2.4    Saving your SAS program

To save your SAS program, ensure that its pane is highlighted and then use the File menu in the usual way.

 

3      The SAS help system

SAS has its own help system that allows you to find out more about the SAS Language, and all

aspects of the software. To access it, select SAS Help and Documentation on the Help menu.4 SAS is a very large software system, and the help system is daunting if you just want help on a    specific command. Even the ‘Quick Search’ is hard to use, because it tends to return large             numbers of possible topics for simple search terms. You will start to get used to it with a bit of    practice. The size of the system also means that it can take a long time (e.g. 10 seconds) to load  the help page for a particular topic: if nothing happens instantly therefore, don’t assume that it   hasn’t responded — it may just be waking up! For this week’s self-study and live sessions, the       following help pages may be useful to you:

•      Help on the SAS DATA step: on the Contents tab of the help system, choose SAS Products -> Base SAS -> SAS 9.4 Language Reference: Concepts, Second

Edition -> DATA Step Concepts. There are several entries here that you can study: under Data Step Processing, the entry on About Creating a SAS Data Set is quite helpful  with several examples.

•      Help on data formats: again on the Contents tab, choose SAS Products -> Base SAS -

> SAS 9.4 Statements Reference, Second Edition -> Dictionary of SAS        Statements -> FORMAT Statement. There are some wordy sections, but the examples are quite helpful. A list of available formats is at SAS Products -> Base SAS -> SAS 9.4     Formats and Informats: Reference -> SAS Formats -> Dictionary of Formats.

•      Help on controlling the appearance of plots: look at SAS Products -> SAS/GRAPH -> Examples -> GPLOT, and Example 4 in particular for examples of controlling the

appearance of scatterplots. To find out how to control the plotting symbols, look at SAS Products -> SAS/GRAPH -> Global Statements -> SYMBOL — if you click ‘Summary of Optional Arguments’ and then ‘VALUE … ’, you’ll see the symbols that are available.

There are some more useful examples of reading data using the DATA step, on the Contents tab under Learning to Use SAS -> Sample SAS Programs -> Base SAS Samples -> Base      Usage Guide Examples. The ‘Introduction to DATA Step Processing’ and ‘Starting with Raw       Data’ sample scripts are quite helpful.


4      Why SAS?

You may have realised that the author of this document is not a big fan of SAS. You may also   wonder why we are teaching it to you. The reason is that it is the preferred statistical software  system for many companies in a variety of industries. This leads to an obvious next question …

there is a

useful online discussion,

which might help to shed some light on the matter.