{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# SAS Formats and Dates\n", "\n", "We previously learned how to use a FORMAT statement to tell SAS to display certain variable values in a particular way. For example, we might tell SAS to display a date variable saledate, say, using the SAS mmddyy10. format, so that August 19, 2008 is displayed as 08/19/2008. There are a whole slew of informats and formats that SAS provides that you can find in the SAS Help and Documentation. Our focus in this lesson will be on creating informats and formats to fill in for those that SAS doesn't provide.\n", "\n", "That is, in this lesson, we will extend our formatting capabilities by investigating how to create user-defined informats and formats using the FORMAT procedure. In particular, we will take a look at the following techniques:\n", "\n", "* how to translate values of a character variable when they are read in a SAS data set into more meaningful values using the INVALUE statement\n", "* how to create customized formats for character and numeric variables, using the VALUE statement, so variables can be printed in a meaningful format\n", "* how to create templates, using the PICTURE statement, for printing numbers with a special format, such as leading zeros, decimal and comma punctuation, fill characters, and prefixes.\n", "\n", "We wil also investigate various aspects of processing dates and times within the SAS System. Specifically, we will learn:\n", "\n", "* how SAS defines numeric date and time values\n", "* how to use informats to read dates and times into a SAS data set\n", "* how to use formats to display SAS dates and times\n", "* how to use dates and times in calculations\n", "* how to compare a SAS date to some date constant, and how to compare a SAS time to some time constant\n", "* how to use several of the available SAS date and time functions\n", "* how to change the system options that pertain to processing date and times\n", "\n", "As always, you'll probably want to follow along in the lesson by downloading and running the provided SAS programs yourself.\n", "\n", "## The Format Procedure\n", "\n", "\n", "\n", "Throughout this section, we will investigate a number of examples that illustrate how to create different informats and formats for several different variables. To do so, we will use a subset of the demographic (or \"background\") data collected on 638 subjects once enrolled in the National Institute of Health's Interstitial Cystitis Data Base (ICDB) Study. Not surprisingly, the ICDB Study collected data on people who were diagnosed as having interstitial cystitis! The primary reason for conducting the study was that interstitial cystitis is a poorly understood condition that causes severe bladder and pelvic pain, urinary frequency, and painful urination in the absence of any identifiable cause. Although the disease is more prevalent in women, it affects both men and women of all ages. For the ICDB Study, each subject was enrolled at one of seven clinical centers and was evaluated four times a year for as many as four years.\n", "\n", "It will probably be helpful for you to take a peek at the background data form on which the data were collected. In order to run the SAS programs in this lesson, you'll need to save the background data set, back.sas7bdat, to a directory on your computer. See the course website for the dataset.\n", "\n", "Because there are 638 observations and 16 variables in the permanent background data set icdb.back, the data on just ten subjects and nine variables are selected when creating the temporary working background data set back. The following SAS program creates the subset:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SAS Connection established. Subprocess id is 5079\n", "\n" ] }, { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

Output Dataset: BACK

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjv_dateb_datesexstatecountryracereligage
111005101/25/9412/02/4224214351.1
211008802/28/9510/03/2722314267.4
321001207/16/9306/27/242.64169.1
422000407/27/9308/07/7223814121.0
523000601/06/9404/24/4922114344.7
631008301/20/9505/13/541.172140.7
741001209/16/9311/01/4722214345.9
842003702/02/9407/25/4122214152.5
951002702/15/9408/14/6324914130.5
1052001711/17/9309/24/5421414139.1
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "LIBNAME phc6089 '/folders/myfolders/SAS_Notes/data/';\n", " \n", "DATA back;\n", " set phc6089.back;\n", " age = (v_date - b_date)/365.25;\n", " if subj in (110051, 110088, 210012, 220004, 230006,\n", " 310083, 410012, 420037, 510027, 520017);\n", " keep subj v_date b_date age sex state country race relig;\n", " format age 4.1;\n", "RUN;\n", " \n", "PROC PRINT data=back;\n", " title 'Output Dataset: BACK';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We'll also need to work with an raw data file version of the subset data set. The following SAS code creates the ascii raw data file, in column format, from the temporary back data set:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "DATA _NULL_;\n", " set back;\n", " file '/folders/myfolders/SAS_Notes/data/back.dat';\n", " put subj 1-6 @8 b_date mmddyy8. sex 17 race 19 \n", " relig 21 state 23-24 country 26-27 \n", " @29 age 4.1 @34 v_date mmddyy8.;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The SAS data set name _NULL_ tells SAS to execute the DATA step as if it were creating a new SAS data set, but no observations and no variables are written to an output data set. The PUT statement tells SAS to write the variables — in the format specified — to the filename specified (back.dat) in the FILE statement. The specifications used in the PUT statement are similar to the specifications used in the INPUT statement.\n", "\n", "Launch the SAS program. Then, edit the FILE statement so it reflects the location where you would like the raw data file saved. Then, run\n", "the program. Open the newly created back.dat file in an ascii editor, such as NotePad, to convince yourself that its structure and contents are similar to the back data set.\n", "\n", "### The INVALUE Statement\n", "\n", "The INVALUE statement in the FORMAT procedure allows you to create your own customized informats for character variables. That is, it allows you to tell SAS how you'd like the program to read in special character values. In doing so, SAS effectively translates the values of a character variable into different, typically more meaningful character or numeric values. For example, the following INVALUE statement:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "INVALUE $french 'OUI'= 'YES' \n", " 'NON'= 'NO'; " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "prepares SAS to translate a character variable in French to a character variable in English.\n", "\n", "Restrictions on the INVALUE statement include:\n", "\n", "* You can only translate a character variable to another variable. You cannot translate a numeric variable using the INVALUE statement.\n", "* The name of the informat must begin with a \\$ sign, since it refers to a character variable.\n", "* The name of the informat (for example, french) must be a valid SAS name with no more than 30 additional characters following the imperative $ sign. The name cannot end in a number nor can the name be a standard SAS informat name.\n", "* When you refer to the informat later, you must follow the name with a period.\n", "\n", "The INVALUE statement in the FORMAT procedure merely defines an informat so that it is available for use. In order for the informat to take effect, you must associate the character variable with the informat either explicitly in the INPUT statement:\n", "\n", "`INPUT resp $french.;`\n", "\n", "or in a FORMAT statement:\n", "\n", "`FORMAT resp $french.; `\n", "\n", "Let's take a look at an example!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

The following SAS code illustrates the use of the FORMAT procedure to define how SAS should translate the two character variables sex and race during input:

\n", "
" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
54   ods listing close;ods html5 (id=saspy_internal) file=stdout options(bitmap_mode='inline') device=svg style=HTMLBlue; ods
54 ! graphics on / outputfmt=png;
NOTE: Writing HTML5(SASPY_INTERNAL) Body file: STDOUT
55
56 PROC FORMAT;
57 invalue $insex '1' = 'M'
NOTE: Informat $INSEX has been output.
58 '2' = 'F';
59
60 invalue $inrace '1' = 'Indian'
61 '2' = 'Asian'
62 '3' = 'Black'
NOTE: Informat $INRACE has been output.
63 '4' = 'White';
64 RUN;
NOTE: PROCEDURE FORMAT used (Total process time):
real time 0.02 seconds
cpu time 0.01 seconds

65
66 ods html5 (id=saspy_internal) close;ods listing;

67
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "PROC FORMAT;\n", " invalue $insex '1' = 'M'\n", " '2' = 'F';\n", " \n", " invalue $inrace '1' = 'Indian'\n", " '2' = 'Asian'\n", " '3' = 'Black'\n", " '4' = 'White';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Because the INVALUE statement is used, the translation is restricted to taking place on input. As a result of this code, providing the character variable sex is later associated with the informat $insex, whenever SAS encounters the character value '1' for the variable sex it will instead store the character value 'M'. Similarly, whenever SAS encounters the character value '2' for the variable sex it will instead store the character value 'F'.

\n", "

Launch and run the SAS program. The only way you'll know if anything happened is by checking out your log window. You should see a message that looks something like what is shown above.

\n", "

As we'll learn later in this lesson, in order to make the definitions for reading in sex and race permanently stored beyond our current work session, we'd need to attach a \"LIBRARY =\" option to the PROC FORMAT statement. Since one doesn't exist here, the definitions defined in this format procedure are temporary only. That is, they are not stored beyond your current SAS session.

\n", "

All we've done so far is define the informats so that they are available for use. Now let's use them!

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

The following data step uses the informats that we defined in the previous example to read in a subset of the data from the input raw data file back.dat:

\n", "
" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

Output Dataset: TEMP1

\n", "
\n", "
\n", "

The CONTENTS Procedure

\n", "
\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Data Set NameWORK.TEMP1Observations10
Member TypeDATAVariables3
EngineV9Indexes0
Created09/24/2020 22:34:56Observation Length16
Last Modified09/24/2020 22:34:56Deleted Observations0
Protection CompressedNO
Data Set Type SortedNO
Label   
Data RepresentationSOLARIS_X86_64, LINUX_X86_64, ALPHA_TRU64, LINUX_IA64  
Encodingutf-8 Unicode (UTF-8)  
\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Engine/Host Dependent Information
Data Set Page Size65536
Number of Data Set Pages1
First Data Page1
Max Obs per Page4061
Obs in First Data Page10
Number of Data Set Repairs0
Filename/tmp/SAS_work6AF500006468_localhost.localdomain/temp1.sas7bdat
Release Created9.0401M6
Host CreatedLinux
Inode Number671542
Access Permissionrw-r--r--
Owner Namesasdemo
File Size128KB
File Size (bytes)131072
\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Alphabetic List of Variables and Attributes
#VariableTypeLen
2raceChar6
1sexChar1
3subjNum8
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "

Output Dataset: TEMP1

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjsexrace
1110051FWhite
2110088FWhite
3210012FWhite
4220004FWhite
5230006FWhite
6310083MAsian
7410012FWhite
8420037FWhite
9510027FWhite
10520017FWhite
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA temp1;\n", " infile '/folders/myfolders/SAS_Notes/data/back.dat';\n", " length sex $ 1 race $ 6;\n", " input subj 1-6 @17 sex $insex1. @19 race $inrace1.;\n", "RUN;\n", " \n", "PROC CONTENTS data=temp1;\n", " title 'Output Dataset: TEMP1';\n", "RUN;\n", " \n", "PROC PRINT data=temp1;\n", " var subj sex race;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Only a subset of the variables in the back.dat data file is read. Column numbers (\"1-6\") are used to read the variable subj, and absolute pointer controls are used to read the variables sex (\"@17\") and race (\"@19\") from the file. Note that:

\n", "
    \n", "
  • Because we want to translate the variables, we must read sex and race as character variables, even though they are numbers.
  • \n", "
  • On input, we have the option of specifying the length of the variables being read in. The length of the variables is specified in the informat name between the name and the period. For example, the length of the variable race being read in is defined as 1 in the informat \\$inrace1.
  • \n", "
  • The LENGTH statement defines the length of sex and race after translation.
  • \n", "
\n", "

Launch the SAS program. Then, edit the INFILE statement so that it reflects the location of your stored back.dat file. Then, run the SAS program and review the output from the CONTENTS and PRINT procedures. In particular, note that the variables sex and race are both character variables, as indicated by \"Char\" appearing under the Type column in the output from the CONTENTS procedure. Also, note that the contents procedure gives no indication that the variables sex and race are formatted in any particular way for output. We'd have to take care of that by using a VALUE statement (as opposed to an INVALUE statement)!

\n", "

Finally, as a little sidebar, recall that the TITLE statement is a toggle statement. That is, its value remains in effect until it is changed with another TITLE statement. Therefore, the title in the PRINT procedure is the same that is used in the CONTENTS procedure.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The VALUE Statement\n", "\n", "The INVALUE statement in the FORMAT procedure allows you to create your own customized informats, so that variables can be **read** in meaningful ways, whereas the VALUE statement allows you to create your own customized formats, so that variables can be **displayed** in meaningful ways. Customized formats do not alter variable types; they merely tell SAS to print variables according to your customized definitions. For example, providing the numeric variable sex is associated with the format sexfmt that is defined in the following VALUE statement:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "VALUE sexfmt 1 = 'Male'\n", " 2 = 'Female';" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "SAS will print \"Male\" when the variable sex = 1 and \"Female\" when sex = 2. The variable type of sex remains numeric. Restrictions on the VALUE statement include:\n", "\n", "* The name of the format for numeric variables (for example, sexfmt) must be a valid SAS name up to 32 characters, not ending in a number.\n", "* The name of the format for a character variable must begin with a \\$ sign, and have no more than 31 additional characters.\n", "* When you **define** the format in the VALUE statement, the format name cannot end in a period.\n", "* But when you **use** the format later, you must follow the name with a period. (Is this confusing or what?)\n", "* The maximum length for a format label is 32,767 characters (ehhhhh...?)\n", "\n", "Just as is true for the INVALUE statement, the VALUE statement in the FORMAT procedure merely defines a format. In order for the format to take effect, you must associate the variable with the format you've defined by using a FORMAT statement in either a DATA step or a PROC step.\n", "\n", "
\n", "

Example

\n", "

The following FORMAT procedure defines how SAS should display numeric variables associated with the two formats sexfmt and racefmt during output:

\n", "
" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", " \n", " \n", " \n", "\n", "\n", "

\n", "\n", "
69   ods listing close;ods html5 (id=saspy_internal) file=stdout options(bitmap_mode='inline') device=svg style=HTMLBlue; ods
69 ! graphics on / outputfmt=png;
NOTE: Writing HTML5(SASPY_INTERNAL) Body file: STDOUT
70
71 PROC FORMAT;
72 value sexfmt 1 = 'Male'
NOTE: Format SEXFMT has been output.
73 2 = 'Female';
74
75 value racefmt 1 = 'Indian'
76 2 = 'Asian'
77 3 = 'Black'
NOTE: Format RACEFMT has been output.
78 4 = 'White';
79 RUN;
NOTE: PROCEDURE FORMAT used (Total process time):
real time 0.00 seconds
cpu time 0.00 seconds

80
81 ods html5 (id=saspy_internal) close;ods listing;

82
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "PROC FORMAT;\n", " value sexfmt 1 = 'Male'\n", " 2 = 'Female';\n", " \n", " value racefmt 1 = 'Indian'\n", " 2 = 'Asian'\n", " 3 = 'Black'\n", " 4 = 'White';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

The translation is restricted to taking place on output, since the VALUE statement is used. As a result of this code, providing the numeric variable sex is later associated with the format sexfmt, whenever SAS goes to print the numeric value 1 for the variable sex, it will instead print the character value 'Male'. Similarly, whenever SAS goes to print the numeric value 2 for the variable sex, it will instead print the character value 'Female'.

\n", "

Launch and run the SAS program. Again, the only way you'll know if anything happened is by checking out your log window. You should see a message that looks something like the one shown above.

\n", "

Again, in order to make the definitions for printing sex and race permanently stored beyond your current work session, you'd need to put a \"LIBRARY =\" option on the PROC FORMAT statement. Since one doesn't exist here, the definitions defined in this FORMAT procedure are temporary only.

\n", "

All we've done so far is define the formats so that they are available for use. Now let's use them!

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

The following SAS code uses the formats to print in a meaningful way the sex and race variables contained in the back data set:

\n", "
" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

Output Dataset: TEMP2

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjsexf_sexracef_race
11100512Female4White
21100882Female4White
32100122Female4White
42200042Female4White
52300062Female4White
63100831Male2Asian
74100122Female4White
84200372Female4White
95100272Female4White
105200172Female4White
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "

Output Dataset: TEMP2

\n", "
\n", "
\n", "

The CONTENTS Procedure

\n", "
\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Data Set NameWORK.TEMP2Observations10
Member TypeDATAVariables11
EngineV9Indexes0
Created09/25/2020 16:32:50Observation Length88
Last Modified09/25/2020 16:32:50Deleted Observations0
Protection CompressedNO
Data Set Type SortedNO
Label   
Data RepresentationSOLARIS_X86_64, LINUX_X86_64, ALPHA_TRU64, LINUX_IA64  
Encodingutf-8 Unicode (UTF-8)  
\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Engine/Host Dependent Information
Data Set Page Size65536
Number of Data Set Pages1
First Data Page1
Max Obs per Page743
Obs in First Data Page10
Number of Data Set Repairs0
Filename/tmp/SAS_work0D27000013D7_localhost.localdomain/temp2.sas7bdat
Release Created9.0401M6
Host CreatedLinux
Inode Number671547
Access Permissionrw-r--r--
Owner Namesasdemo
File Size128KB
File Size (bytes)131072
\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Alphabetic List of Variables and Attributes
#VariableTypeLenFormat
9ageNum84.1
3b_dateNum8MMDDYY8.
6countryNum8 
10f_raceNum8RACEFMT.
11f_sexNum8SEXFMT.
7raceNum8 
8religNum8 
4sexNum8 
5stateNum8 
1subjNum8 
2v_dateNum8MMDDYY8.
\n", "
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA temp2;\n", " set back;\n", " f_race=race; \n", " f_sex=sex;\n", " format f_race racefmt. f_sex sexfmt.;\n", "RUN;\n", " \n", "PROC PRINT data=temp2;\n", " title 'Output Dataset: TEMP2';\n", " var subj sex f_sex race f_race;\n", "RUN;\n", " \n", "PROC CONTENTS data=temp2;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Well, that's not precisely true! First, in creating the new data set temp2 from the back data set, two additional (numeric) variables are created, f_sex and f_race. They are equated, respectively, to the variables sex and raceassociates the f_race variable with the racefmt. format and the f_sex variable with the sexfmt. format. Again, just as is true for SAS formats, you can place the FORMAT statement in either a DATA step or a PROC step. If you place the FORMAT in a PROC step, the format is associated with the variable only for the procedure in which the association is made. If you instead place the FORMAT statement in a DATA step, the format becomes available for all subsequent procedures.

. Just as with SAS formats, you must associate a user-defined format with a variable in a FORMAT statement. The FORMAT statement:

\n", "
format f_race racefmt. f_sex sexfmt.;
\n", "

associates the f_race variable with the racefmt. format and the f_sex variable with the sexfmt. format. Again, just as is true for SAS formats, you can place the FORMAT statement in either a DATA step or a PROC step. If you place the FORMAT in a PROC step, the format is associated with the variable only for the procedure in which the association is made. If you instead place the FORMAT statement in a DATA step, the format becomes available for all subsequent procedures.

\n", "

Incidentally, note that it is not necessary to create a formatted and unformatted version of the same variables as we did in this example merely for educational purposes. Creating two versions of the same variables merely helps us see the effect the formatting has on the sex and race variables.

\n", "

Launch and run the SAS program and review the output from the CONTENTS and PRINT procedures. In particular, observe the difference in the printed output between the formatted and unformatted versions of the variables f_sex and sex (and f_race and race). Also, note that the CONTENTS procedure indicates that the variables sex and race are unformatted, numeric variables (since there is no special format specified), while f_sex and f_race are formatted, numeric variables (a special format is specified).

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

The FORMAT procedure is useful in defining meaningful categories once you've converted one or more (perhaps continuous) variables into one categorical variable. The following SAS code illustrates the technique:

\n", "
" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

Age Frequency in TEMP3

\n", "
\n", "
\n", "

The FREQ Procedure

\n", "
\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
age2FrequencyPercentCumulative
Frequency
Cumulative
Percent
20-44550.00550.00
45-54330.00880.00
GE 54220.0010100.00
\n", "
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "PROC FORMAT;\n", " value age2fmt 1 = 'LT 20'\n", " 2 = '20-44'\n", " 3 = '45-54'\n", " 4 = 'GE 54'\n", " OTHER = 'Missing';\n", "RUN;\n", " \n", "DATA temp3;\n", " set back;\n", " if age = . then age2 = .;\n", " else if age lt 20 then age2 = 1;\n", " else if age ge 20 and age lt 45 then age2 = 2;\n", " else if age ge 45 and age lt 54 then age2 = 3;\n", " else if age ge 54 then age2 = 4;\n", " format age2 age2fmt.;\n", "RUN;\n", " \n", "PROC FREQ data=temp3;\n", " title 'Age Frequency in TEMP3';\n", " table age2;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

The FORMAT procedure defines the AGE2FMT format, so that ages are groups into five categories: less than 20, 20-44, 45-54, 54 or greater, and missing. The special range keyword OTHER groups all other age values into one single gropu. Since, here, a missing value is the only other possible, values falling in the OTHER category are labeled \"Missing\".

\n", "

The data set temp3 is derived from the back dataset. The only difference between these two datasets is that the new variable age2 is created in temp3 using an if-then-else statement to group values of age. The format statement associates the variable age2 with the format age2fmt defined in the FORMAT procedure. Note that the if statement codes for missing ages. If this were not done, missing ages would be incorrectly coded as 1 and output as \"LT 20\".

\n", "

The FREQ procedure determines the frequencies of the various levels of the categorical variable defined in the TABLE statement. Since only one variable (age2) is identified in the TABLE statement, SAS oututs one table which contains the number of subjects with age < 20, between 20 and 44, between 45 and 54, greater than or equal to 54, and missing. Note that any categories that have a 0 count (LT 20 and Missing) are not shown in the table.

\n", "

Launch and run the program and review the original data set as well as the output from the FREQ procedure to convince yourself that the age categories have been appropriately labeled.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

Now, as long as we are interested in grouping values of only one variable, rather than doing it as we did in the previous program, we can actually accomplish it a bit more efficiently directly within the FORMAT procedure. For example, the following SAS code uses the FORMAT procedure to define the format agefmt based on the possible values of the variable age:

\n", "
" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

Age Frequency in BACK

\n", "
\n", "
\n", "

The FREQ Procedure

\n", "
\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
ageFrequencyPercentCumulative
Frequency
Cumulative
Percent
20-44550.00550.00
45-54330.00880.00
GE 54220.0010100.00
\n", "
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "PROC FORMAT;\n", " value agefmt LOW-<20 = 'LT 20'\n", " 20-<45 = '20-44'\n", " 45-<54 = '45-54'\n", " 54-HIGH = 'GE 54'\n", " OTHER = 'Missing';\n", "RUN;\n", " \n", "PROC FREQ data=back;\n", " title 'Age Frequency in BACK';\n", " format age agefmt.;\n", " table age;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

In defining groups of values right within the FORMAT procedure, note that as illustrated in this program:

\n", "
    \n", "
  • The potential ranges are defined using a dash (-). You can also list a range of values by separating the values with commas: 1,2,3 = 'Low'
  • \n", "
  • The < symbol means \"not including.\" Therefore, here for example, 20-<45 means all ages between 20 and 45, including 20, but not including 45.
  • \n", "
  • The special LOW and HIGH ranges allow you to group values without knowing the smallest and largest values, respectively. (The keyword LOW does not include missing numeric values, but if applied to a character format, it does include missing character values.)
  • \n", "
\n", "

The FREQ procedure tallies the number of subjects falling within each of the age groups as defined in the FORMAT procedure. Here, the variable age is associated with the format agefmt using a FORMAT statement right within the FREQ procedure.

\n", "

Now, launch and run the program and review the original data set as well as the output from the frequency procedure to convince yourself that the age categories have again been appropriately labeled.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Permanent Formats\n", "\n", "All of the customized informat and format definitions in this lesson thus far have been stored only temporarily. That is, the informats and formats are valid only for the duration of the SAS session in which they are defined. If you wanted to use the informats or formats again in a different SAS program, you would have to create them again using another FORMAT procedure. If you plan to use a customized informat or format repeatedly, you can store it permanently in a \"**formats catalog**\" by using the LIBRARY= option in the PROC FORMAT statement. Basically, the LIBRARY= option tells SAS where the formats catalog is (to be) stored. You tell SAS the library (which again you can think of as a directory or location) by using a LIBNAME statement:\n", "\n", "`LIBNAME libref 'c:\\directory\\where\\formats\\stored';`\n", "\n", "where libref is technically a name of your choosing. Note though that when a user-defined informat or format is called by a DATA or PROC step, SAS first looks in a temporary catalog named work.formats. (Recall that \"work\" is what SAS always treats as your temporary working library that goes away at the end of your SAS session.) If SAS does not find the format or informat in the temporary catalog, it then by default looks in a permanent catalog called library.formats. So, while, yes, **libref** is technically a name of your choosing, it behooves you to call it library since that what SAS looks for first. That's why SAS recommends, but does not require, that you use the word library as the libref when creating permanent formats.\n", "\n", "To make this blather a bit more concrete, suppose we have the following LIBNAME statement in our SAS program:\n", "\n", "`LIBNAME library 'C:\\Simon\\Stat480WCDEV\\08format\\sasndata\\';`\n", "\n", "and have a format procedure that starts with:\n", "\n", "`PROC FORMAT library=library;`\n", "\n", "Then, upon running the program, SAS creates a permanent catalog containing all of the formats and informats that are defined in the FORMAT procedure and stores it in the folder referenced above, as illustrated here:\n", "\n", "![Format definition file in file location defined in the LIBNAME statement.](./img/formats_library_loc.gif)\n", "\n", "A formats catalog, regardless of whether it is temporary (work.formats) or permanent (library.formats), contains one entry for each format or informat defined in a FORMAT procedure. Because library.formats is the reserved name for permanent formats catalogs, you can create only one catalog called formats per SAS library (directory). There are ways around this restriction, but let's not get into that now. Let's jump to an example instead." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

The following SAS program illustrates a FORMAT procedure that creates a permanent formats catalog in the directory referenced by library, that is, in /folders/myfolders/SAS_Notes/data:

\n", "
" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

Output Dataset: TEMP4

\n", "
\n", "
\n", "

The CONTENTS Procedure

\n", "
\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Data Set NameWORK.TEMP4Observations10
Member TypeDATAVariables3
EngineV9Indexes0
Created09/25/2020 20:57:10Observation Length24
Last Modified09/25/2020 20:57:10Deleted Observations0
Protection CompressedNO
Data Set Type SortedNO
Label   
Data RepresentationSOLARIS_X86_64, LINUX_X86_64, ALPHA_TRU64, LINUX_IA64  
Encodingutf-8 Unicode (UTF-8)  
\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Engine/Host Dependent Information
Data Set Page Size65536
Number of Data Set Pages1
First Data Page1
Max Obs per Page2714
Obs in First Data Page10
Number of Data Set Repairs0
Filename/tmp/SAS_work0D27000013D7_localhost.localdomain/temp4.sas7bdat
Release Created9.0401M6
Host CreatedLinux
Inode Number671549
Access Permissionrw-r--r--
Owner Namesasdemo
File Size128KB
File Size (bytes)131072
\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Alphabetic List of Variables and Attributes
#VariableTypeLenFormat
3raceNum8RACE2FMT.
2sexNum8SEX2FMT.
1subjNum8 
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "

Output Dataset: TEMP4

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjsexrace
1110051FemaleWhite
2110088FemaleWhite
3210012FemaleWhite
4220004FemaleWhite
5230006FemaleWhite
6310083MaleOther
7410012FemaleWhite
8420037FemaleWhite
9510027FemaleWhite
10520017FemaleWhite
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "LIBNAME library '/folders/myfolders/SAS_Notes/data';\n", " \n", "PROC FORMAT library=library;\n", " value sex2fmt 1 = 'Male'\n", " 2 = 'Female';\n", " \n", " value race2fmt 3 = 'Black'\n", " 4 = 'White'\n", " OTHER = 'Other';\n", "RUN;\n", " \n", "DATA temp4; \n", " infile '/folders/myfolders/SAS_Notes/data/back.dat';\n", " input subj 1-6 sex 17 race 19;\n", " format sex sex2fmt. race race2fmt.;\n", "RUN;\n", " \n", "PROC CONTENTS data=temp4;\n", " title 'Output Dataset: TEMP4';\n", "RUN;\n", " \n", "PROC PRINT data=temp4;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

The DATA step creates a temporary data set called temp4 by reading in the variables subj, sex, and race from the raw data file back.dat, and associates the variables sex and race, respectively, with the formats sex2fmt and race2fmt that are defined in the FORMAT procedure. SAS first looks for the occurrence of these two formats in the temporary catalog work.formats and then when it doesn't find them there, it looks for them in the catalog of the permanent format in the /folders/myfolders/SAS_Notes/data directory.

\n", "

Launch the SAS program, and edit the INFILE statement so it reflects the location of your back.dat file. And, edit the LIBNAME statement so it reflects your desired location for the catalog of the permanent format. Then, run the program and review the output from the CONTENTS and PRINT procedures to convince yourself that the variables sex and race are associated with the permanent formats sex2fmt and race2fmt, not the temporary formats sexfmt and racefmt previously associated with f_sex and f_race. Also, view the directory referenced in your LIBNAME statement to convince yourself that SAS created and stored a permanent formats catalog there.

\n", "

Just a few more comments on this permanent formats stuff. One of the problems with permanent informats and formats is that once a variable has been associated permanently with an informat or format, SAS must be able to refer to the library to access the formats catalog. As long as the formats catalog exists, and you have permission to the file, you just have to specify the appropriate LIBNAME statement:

\n", "
LIBNAME library '/folders/myfolders/SAS_Notes/data';
\n", "

to access the catalog. If for some reason, you do not have access to the formats catalog, SAS will give you an error that looks something like this:

\n", " \"SAS\n", "

If you specify the NOFMTERR in the OPTIONS statement:

\n", "
OPTIONS NOFMTERR;
\n", "

you can use the SAS data sets without getting errors. SAS will just display a note (not a program-halting error!) in the log file:

\n", " \"SAS\n", "

You will be able to run SAS programs that use the data sets containing the permanent formats. You will just not have access to the formats.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

Rather than creating a permanent formats catalog, you can create a SAS program file which contains only a FORMAT procedure with the desired value and invalue statements. Then you need merely include this secondary program file in your main SAS program using the %INCLUDE statement, as illustrated here:

\n", "
" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

Frequency Count of STATE (statefmt)

\n", "
\n", "
\n", "

The FREQ Procedure

\n", "
\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
stateFrequencyPercentCumulative
Frequency
Cumulative
Percent
Missing220.00220.00
Ind110.00330.00
Mass110.00440.00
Mich220.00660.00
Minn110.00770.00
Other110.00880.00
Tenn110.00990.00
Wisc110.0010100.00
\n", "
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%INCLUDE '/folders/myfolders/SAS_Notes/data/backfmt.sas';\n", " \n", "PROC FREQ data=back;\n", " title 'Frequency Count of STATE (statefmt)';\n", " format state statefmt.;\n", " table state / missing;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

To make it clear, here's the only thing contained in the backfmt.sas file:

\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "PROC FORMAT;\n", " value statefmt 14 = 'Ind'\n", " 21 = 'Mass'\n", " 22 = 'Mich'\n", " 23 = 'Minn'\n", " 42 = 'Tenn'\n", " 49 = 'Wisc'\n", " . = 'Missing'\n", " Other = 'Other';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Since the FORMAT procedure in the backfmt.sas file does not refer to a permanent library, the format statefmt is stored in the temporary work.formats catalog.

\n", "

To run this program, first download and save the backfmt.sas (see the data folder in CANVAS) file to a convenient location on your computer. Then, launch the SAS program and edit the %INCLUDE statement so it reflects the location of your backfmt.sas file. Finally, run the program and review the output from the FREQ procedure. Convince yourself that the format statement in the FREQ procedure appropriately associates the state variable with the statefmt format created by the FORMAT procedure in backfmt.sas. You may as well also take note of the effect of the MISSING option in the FREQ procedure. Basically, it tells SAS to include missing values as a countable category.

\n", "

The technique illustrated in this example is particularly useful when you work in an open environment, in which data sets are shared. Different users may not have access to the format file, or different users may prefer different formats.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Using Codebooks to Help Define Formats\n", "\n", "It is very common for discrete (categorical) variables to have many, many (hundreds, perhaps even thousands of) possible values. Examples include:\n", "\n", "* diseases may be coded by an integer\n", "* surgical treatments may be coded by an integer\n", "* medications may be coded by an integer\n", "\n", "An electronic \"**codebook**\" is typically used to keep track of the meaning of each of the integer codes. That is, codebooks contain two variables, the code and a text description of the code. For example, disease 1124 could be defined in text as \"Rheumatoid Arthritis.\"\n", "\n", "One would find it extremely tedious and time-consuming to have to type a FORMAT procedure which re-defines the codes and text contained in these codebooks. Instead, one can take advantage of the fact that the codebook is already in an electronic format, such as a database table, an ascii file, or even a SAS data set.\n", "\n", "When the codebook is contained in a SAS data set with three required variables:\n", "\n", "* start: the variable that contains the starting range values (that is, the codes)\n", "* label: the variable that contains the text definition\n", "* fmtname: the format name\n", "\n", "SAS can create the appropriate format using the CNTLIN = option in the PROC FORMAT statement. Let's take a look at an example.\n", "\n", "
\n", "

Example

\n", "

The following SAS program creates a SAS data set called states from state_cd, which is the codebook for the variable state that is collected on the ICDB background form. Here's what the first ten observations of the state_cd data set look like:

\n", "
" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

Codebook for States

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
ObsNAMECODE
1alabama1
2alaska2
3arizona3
4arkansas4
5california5
6colorado6
7connecticut7
8delaware8
9florida9
10georgia10
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "PROC PRINT data=phc6089.state_cd(obs=10);\n", " title 'Codebook for States';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

The data set states is then used in the FORMAT procedure to define the format for the variable state in the back data set:

\n", "
" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

Freqency Count of STATE (stat2fmt)

\n", "
\n", "
\n", "

The FREQ Procedure

\n", "
\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
stateFrequencyPercentCumulative
Frequency
Cumulative
Percent
Frequency Missing = 2
indiana112.50112.50
massachusetts112.50225.00
michigan225.00450.00
minnesota112.50562.50
pennsylvania112.50675.00
tennessee112.50787.50
wisconsin112.508100.00
\n", "
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA states;\n", " set phc6089.state_cd (rename = (code = start name=label));\n", " fmtname = 'stat2fmt';\n", "RUN;\n", " \n", "PROC FORMAT cntlin=states;\n", "RUN;\n", " \n", "PROC FREQ data=back;\n", " title 'Freqency Count of STATE (stat2fmt)';\n", " format state stat2fmt.;\n", " table state;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Before running this program, you'll have to download the codebook state_cd (see the data folder on the course website). Save it to the location on your computer that you referenced in the earlier LIBNAME statement by the libref phc6089. Then, go ahead and launch and run the program.

\n", "

As you can see from the output, the PRINT procedure merely prints the (first 10 rows of the) phc6089.state_cd codebook for your review. You should notice that the variable names in state_cd do not meet SAS requirements for codebooks. Therefore, the DATA step that creates the data set states merely renames the code and name variables in phc6089.state_cd so that they meet SAS requirements. The RENAME= option on the SET statement is what is used to change the code variable to start and the name variable to label. The general syntax of the RENAME= option on the SET statement is:

\n", "
set dsname (rename = (oldvr1 = newvr1 oldvr2 = newvr2 ...));
\n", "

An assignment statement is then used to assign the value stat2fmt to the variable fmtname for each observation (that is, code) that appears in the phc6089.state_cd data set.

\n", "

Then, the FORMAT procedure with the CNTLIN = states option tells SAS to create the format stat2fmt based on the contents of the data set states. Finally, the FREQ procedure illustrates the use of the stat2fmt after it was created in this manner. SAS merely counts and reports the number of subjects coming from each of the states. Note that since we didn't include the MISSING option on the TABLE statement, SAS reports the number of missing values after the table, rather than as a row of the table.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The FMTLIB Option\n", "\n", "You might have taken note that the FORMAT procedure by itself does not generate any output. Indeed, the FORMAT procedure prints output only when you specify the FMTLIB option in the PROC FORMAT statement. The FMTLIB option of the FORMAT procedure tells SAS to display a list of all the formats and/or informats in your catalog, along with desciptions of their values. The FMTLIB option can be particularly helpful when you are working with a large catalog of formats, and have forgotten the exact spelling of a specific format name or its range of values.\n", "\n", "
\n", "

Example

\n", "

The following code uses the FORMAT procedure's FMTLIB option to request that SAS display information about three formats appearing in the work.format catalog:

\n", "
" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

Selected Formats from WORK.FORMAT Catalog

\n", "
\n", "
\n", "
\n",
       "                            ----------------------------------------------------------------------------                            \n",
       "                            |       FORMAT NAME: RACEFMT  LENGTH:    6   NUMBER OF VALUES:    4        |                            \n",
       "                            |   MIN LENGTH:   1  MAX LENGTH:  40  DEFAULT LENGTH:   6  FUZZ: STD       |                            \n",
       "                            |--------------------------------------------------------------------------|                            \n",
       "                            |START           |END             |LABEL  (VER. V7|V8   25SEP2020:16:30:29)|                            \n",
       "                            |----------------+----------------+----------------------------------------|                            \n",
       "                            |               1|               1|Indian                                  |                            \n",
       "                            |               2|               2|Asian                                   |                            \n",
       "                            |               3|               3|Black                                   |                            \n",
       "                            |               4|               4|White                                   |                            \n",
       "                            ----------------------------------------------------------------------------                            \n",
       "
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "PROC FORMAT FMTLIB;\n", " title 'Selected Formats from WORK.FORMAT Catalog';\n", " select racefmt;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Launch and run the SAS program and review the output. Since the FORMAT procedure here does not refer to a permanent library, the contents of the temporary work.formats catalog are printed. The SELECT statement tells SAS to print information only on a select few formats rather than on the entire catalog. (See SAS Help for more details on the SELECT statement and its sister EXCLUDE statement.)

\n", "

Although not used in this example, the PAGE option may be used additionally to tell SAS to print the information about each format and informat in the catalog on a separate page.

\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "PROC FORMAT FMTLIB PAGE;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

The FORMAT procedure's PAGE option is meaningless unless the FMTLIB option is also invoked.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Date and Time Processing\n", "\n", "SAS stores dates as single, unique numbers, so that they can be used in your programs like any other numeric value. Specifically, SAS stores dates as numeric values equal to the number of days from January 1, 1960. That is, dates prior to January 1, 1960 are stored as unique negative integers, and dates after January 1, 1960 are stored as unique positive integers. So, for example, SAS stores:\n", "\n", "* a 0 for January 1, 1960 \n", "* a 1 for January 2, 1960\n", "* a 2 for January 3, 1960\n", "* and so on ...\n", "\n", "And, SAS stores:\n", "\n", "* a -1 for December 31, 1959\n", "* a -2 for December 30, 1959\n", "* a -3 for December 29, 1959\n", "* and so on ...\n", "\n", "No matter what method is used in creating a SAS date, SAS always converts the date to an integer as just defined.\n", "\n", "### Date Informats and Formats\n", "\n", "In order to read variables that are dates, we need to tell SAS what form the date takes. For example, is the date in the form Dec 1, 2005? Or is it 12/01/05? Or 01 December 2005? The form that a date takes on input is known as a date informat. There seem to be as many SAS date informats as there are ways that you could imagine writing a date. Well, okay, maybe not quite that many. We'll take a look at several of the informats that are available in SAS later in this lesson. For now, we'll just refresh our memory of how to write the formatted style input statement that is necessary to read in dates.\n", "\n", "
\n", "

Example

\n", "

The following SAS program reads five observations into a SAS data set called diet. Two of the variables — weight date (wt_date) and birth date (b_date) — are in mm/dd/yy format, and therefore SAS is told to read the dates using the mmddyy8. informat:

\n", "
" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The unformatted diet data set

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjl_nameweightwt_dateb_date
11024Smith125167710
21167White14016771-365
31168Jones19016772166
41201Arnold19016770365
51302Ho11516802-565
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA diet;\n", " input subj 1-4 l_name $ 18-23 weight 30-32\n", " +1 wt_date mmddyy8. @43 b_date mmddyy8.;\n", " DATALINES;\n", "1024 Alice Smith 1 65 125 12/1/05 01/01/60\n", "1167 Maryann White 1 68 140 12/01/05 01/01/59\n", "1168 Thomas Jones 2 190 12/2/05 06/15/60\n", "1201 Benedictine Arnold 2 68 190 11/30/05 12/31/60\n", "1302 Felicia Ho 1 63 115 1/1/06 06/15/58\n", ";\n", "RUN;\n", " \n", "PROC PRINT data=diet;\n", " TITLE 'The unformatted diet data set';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First, note that the mmddyy8. informat must immediately follow the date's variable name. Here, it immediately follows wt_date, and then again follows b_date. Incidentally, the 8 in mmddyy8. defines, in general, the width of the informat. It tells SAS that the dates to be read into SAS contain as many as 8 positions. Here, two of the positions are taken up by forward slashes (/). You could alternatively use hypens (-) or blank spaces between the mm and dd and yy. Also note that the period is a very important part of the informat name. Without it, SAS may attempt to interpret the informat as a variable name instead.

\n", "

Then, launch and run the SAS program, and review the resulting output to familiarize yourself with the contents of the diet data set. Note, in particular, the numeric values that are stored for the wt_date and b_date variables. As expected, the 01/01/60 birth date is stored as a 0, the 01/01/59 birthdate is stored as -365, and the 12/31/60 birthdate is stored as +365. Well, geez, I guess the other thing that the output illustrates is that it is not enough just to tell SAS what informat to use to read in a date's value, but you also have to tell SAS what format to use to display a date's value. If you don't, as you see here, the dates that are displayed are not particularly user-friendly!

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

As the preceding example illustrates, we have to tell SAS in what form we would like our dates displayed. The form that a date takes in output is known as a date format. Do we want the date displayed in the form Dec 1, 2005? Or 12/01/05? Or 01 December 2005? Again, there seem to be as many SAS date formats as there are ways that you could imagine writing a date. To tell SAS in which form we want our dates displayed, we use a FORMAT statement.

\n", "\n", "
\n", "

Example

\n", "

The following SAS program is identical to the previous program, except a FORMAT statement has been added to tell SAS to display the wt_date and b_date variables in date7. format:

\n", "
" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The formatted diet data set

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjl_nameweightwt_dateb_date
11024Smith12501DEC0501JAN60
21167White14001DEC0501JAN59
31168Jones19002DEC0515JUN60
41201Arnold19030NOV0531DEC60
51302Ho11501JAN0615JUN58
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA diet;\n", "input subj 1-4 l_name $ 18-23 weight 30-32\n", " +1 wt_date mmddyy8. @43 b_date mmddyy8.;\n", "format wt_date b_date date7.;\n", "DATALINES;\n", "1024 Alice Smith 1 65 125 12/1/05 01/01/60\n", "1167 Maryann White 1 68 140 12/01/05 01/01/59\n", "1168 Thomas Jones 2 190 12/2/05 06/15/60\n", "1201 Benedictine Arnold 2 68 190 11/30/05 12/31/60\n", "1302 Felicia Ho 1 63 115 1/1/06 06/15/58\n", " ;\n", "RUN;\n", " \n", "PROC PRINT data=diet;\n", " title 'The formatted diet data set';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First, take note of the FORMAT statement in which the selected format date7. follows the two variables — wt_date and b_date — whose values we want displayed as ddMonyy. Then, launch and run the SAS program, and review the resulting output to convince yourself of the effect of the FORMAT statement.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

The best thing about SAS dates is that, because SAS date values are numeric values, you can easily sort them, subtract them, and add them. You can also compare dates. Or, you can use them in many of the available numeric functions.

\n", "\n", "
\n", "

Example

\n", "

The following SAS program illustrates how you can treat date variables as any other numeric variable, and therefore can use the dates in numeric calculations. Assuming that individuals in the diet data set need to be weighed every 14 days, a new variable nxt_date, the anticipated date of the individual's next visit, is determined by merely adding 14 to the individual's current weight date (wt_date). Then, a crude estimate of each individual's age is also calculated by subtracting b_date from wt_date and dividing the resulting number of days by 365.25 to get an approximate age in years. And, the MEAN function is used to calculate avg_date, the average of each individual's birth and weight dates:

\n", "
" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The diet data set with three new variables

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjl_nameweightwt_dateb_datenxt_dateage_wtavg_date
11024Smith12501DEC0501JAN6015DEC0545.916DEC82
21167White14001DEC0501JAN5915DEC0546.917JUN82
31168Jones19002DEC0515JUN6016DEC0545.510MAR83
41201Arnold19030NOV0531DEC6014DEC0544.916JUN83
51302Ho11501JAN0615JUN5815JAN0647.524MAR82
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA diet;\n", " input subj 1-4 l_name $ 18-23 weight 30-32\n", " +1 wt_date mmddyy8. @43 b_date mmddyy8.;\n", " nxt_date = wt_date + 14;\n", " age_wt = (wt_date - b_date)/365.25;\n", " avg_date = MEAN(wt_date, b_date);\n", " format wt_date b_date nxt_date avg_date date7. \n", " age_wt 4.1; \n", " DATALINES;\n", "1024 Alice Smith 1 65 125 12/1/05 01/01/60\n", "1167 Maryann White 1 68 140 12/01/05 01/01/59\n", "1168 Thomas Jones 2 190 12/2/05 06/15/60\n", "1201 Benedictine Arnold 2 68 190 11/30/05 12/31/60\n", "1302 Felicia Ho 1 63 115 1/1/06 06/15/58\n", " ;\n", "RUN;\n", " \n", "PROC PRINT data=diet;\n", " title 'The diet data set with three new variables';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First, review the code to see how the three new variables — nxt_date, age_wt and avg_date — are calculated using standard numeric expressions. You should also acknowledge that the calculation of avg_date is just a desperate attempt by a desperate instructor to illustrate the use of dates in a standard numeric function, and is otherwise probably fairly useless. Then, launch and run the SAS program, and review the resulting output to convince yourself that the results of the calculations seem reasonable.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

The following SAS program illustrates again how you can treat date variables as any other numeric variable, and therefore can sort dates. The diet data set is sorted by nxt_date in ascending order, so that the individuals whose next weigh-in date is closest in time appear first:

\n", "
" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The diet data set sorted by nxt_date

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjl_nameweightwt_dateb_datenxt_dateage_wtavg_date
11201Arnold19030NOV0531DEC6014DEC0544.916JUN83
21024Smith12501DEC0501JAN6015DEC0545.916DEC82
31167White14001DEC0501JAN5915DEC0546.917JUN82
41168Jones19002DEC0515JUN6016DEC0545.510MAR83
51302Ho11501JAN0615JUN5815JAN0647.524MAR82
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "PROC SORT data = diet out = sorteddiet;\n", " by nxt_date;\n", "RUN;\n", " \n", "PROC PRINT data = sorteddiet;\n", " TITLE 'The diet data set sorted by nxt_date';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First review the code, and then launch and run the SAS program. Then, review the resulting output to convince yourself that the variable nxt_date is sorted as indeed claimed.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Again, because SAS date values are numeric values, you can easily compare two or more dates. The comparisons are made just as the comparisons between any two numbers would take place. For example, because the date 01/03/60 is stored as a 2 in SAS, it is considered smaller than the date 01/10/60, which is stored as a 9 in SAS.

\n", "\n", "
\n", "

Example

\n", "

The following SAS program illustrates how to compare the values of a date variable, not to the values of some other date variable, but rather to a date constant. Specifically, the WHERE= option that appears on the DATA statement tells SAS to output to the diet data set only those individuals whose b_date is before January 1, 1960:

\n", "
" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

Birthdays in the diet data set before 01/01/1960

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjl_nameweightwt_dateb_date
11167White14001DEC200501JAN1959
21302Ho11501JAN200615JUN1958
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA diet (where = (b_date < '01jan1960'd));\n", " input subj 1-4 l_name $ 18-23 weight 30-32\n", " +1 wt_date mmddyy8. @43 b_date mmddyy8.;\n", " format wt_date b_date date9.;\n", " DATALINES;\n", "1024 Alice Smith 1 65 125 12/1/05 01/01/60\n", "1167 Maryann White 1 68 140 12/01/05 01/01/59\n", "1168 Thomas Jones 2 190 12/2/05 06/15/60\n", "1201 Benedictine Arnold 2 68 190 11/30/05 12/31/60\n", "1302 Felicia Ho 1 63 115 1/1/06 06/15/58\n", ";\n", "RUN;\n", " \n", "PROC PRINT data=diet;\n", " title 'Birthdays in the diet data set before 01/01/1960';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First, note the form of the SAS date constant:

\n", "
'01jan1960'd
\n", "

used in the WHERE= option. In general, a SAS date constant takes the form 'ddMONyyyy'd where dd denotes the day of the month (0, ..., 31), MON denotes the first three letters of the month, and yyyy denotes the four-digit year. The letter d that follows the date in single quotes tells SAS to treat the date string like a constant. Note that regardless of how you have informatted or formatted your SAS dates, the SAS date constant always takes the above form.

\n", "

Now, launch and run the SAS program. Then, review the resulting output to convince yourself that only those individuals whose birth date is before January 1, 1960 are included in the output diet data set. You might also want to note the difference between the date7. and date9. format. Previously, we saw that when you use the date7. format, your dates are displayed in ddMonyy format. Here, you can see that when you use the date9. format, your dates are displayed in ddMonyyyy format. (Incidentally, I think it is a good practice to use four-digit years wherever possible to avoid any ambiguity.) We'll take a look at some of the other informats and formats available later in this lesson. Now, we'll go take a look at some of the available functions that work specifically with SAS dates.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Throughout this lesson so far, we have used the mmddyy8. informat to read in SAS dates. And, we have used the date7. and date9. formats to display SAS dates. In this section, we'll just take a look at a few quick examples to illustrate some of the other informats and formats available in SAS." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

The following SAS program reads in three dates (date1, date2, and date3) using an mmddyy informat. Then, the dates are printed using a ddmmyy format:

\n", "
" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The mmddyy informat and the ddmmyy format

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obsdate1date2date3
110/04/200810 04 200810:04:2008
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA inputdates1;\n", " INPUT @6 date1 mmddyy6. @13 date2 mmddyy8. @22 date3 mmddyy10.;\n", " FORMAT date1 ddmmyy10. date2 ddmmyyb10. date3 ddmmyyc10.;\n", " DATALINES;\n", " 041008 04-10-08 04 10 2008\n", " ;\n", "RUN;\n", " \n", "PROC PRINT data = inputdates1;\n", " TITLE 'The mmddyy informat and the ddmmyy format';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First, review the INPUT statement and the corresponding forms of the April 10, 2008 date in the DATALINES statement. Note, in particular, that the width of the mmddyy informat (6, 8, or 10) tells SAS what form of the date it should expect. Don't worry — SAS will let you know if you misspecify the width of the format! Also, note that the way that we format dates can be completely independent of the way that they are informatted. Here, the dates are read in using the mmddyy informat and are displayed in the rearranged ddmmyy format. Well, let's be a little more specific here about that ddmmyy format. The \"b\" that appears in the format for the date2 variable tells SAS to display blank spaces between the month, day and year. The \"c\" that appears in the format for the date3 variable tells SAS to display colons between the month, day and year. If nothing appears (or alternatively an \"s\") in a ddmmyy format, as it does here for the date1 variable, SAS will display forward slashes between the month, day and year.

\n", "

When you are satisfied you understand the use of the mmddyy informat and the ddmmyy format, launch and run the SAS program. Review the output to convince yourself that the program does as claimed.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

The following SAS program reads in three dates (date1, date2, and date3) using a ddmmyy informat. Then, the dates are printed using a mmddyy format:

\n", "
" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The ddmmyy informat and the mmddyy format

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obsdate1date2date3
104-10-20080410200804.10.2008
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA inputdates2;\n", " INPUT @6 date1 ddmmyy6. @13 date2 ddmmyy8. @22 date3 ddmmyy10.;\n", " FORMAT date1 mmddyyd10. date2 mmddyyn8. date3 mmddyyp10.;\n", " DATALINES;\n", " 100408 10-04-08 10 04 2008\n", ";\n", "RUN;\n", " \n", "PROC PRINT data = inputdates2;\n", " TITLE 'The ddmmyy informat and the mmddyy format';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First, review the INPUT statement and the corresponding forms of the April 10, 2008 date in the DATALINES statement. Again, the width of the ddmmyy informat (6, 8, or 10) tells SAS what form of the date it should expect. The \"d\" that appears in the format for the date1 variable tells SAS to display dashes between the month, day and year. The \"n\" that appears in the format for the date2 variable tells SAS to display nothing between the month, day and year. (Note that the width of the mmddyyn8. format is 8, and not 10. If you specify a width of 10 with the \"n\" extension, SAS will hiccup.) The \"p\" that appears in the format for the date3 variable tells SAS to display periods between the month, day and year.

\n", "

When you are satisfied you understand the use of the ddmmyy informat and the mmddyy format, launch and run the SAS program. Review the output to convince yourself that the program does as claimed.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

The following SAS program reads in three dates (date1, date2, and date3) using a date informat. Then, the dates are printed using weekdate, worddate, and worddatx formats, respectively:

\n", "
" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The date7 informat and the weekdate and worddate formats

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obsdate1date2date3
1Thursday, Apr 10, 2008April 10, 200810 April 2008
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA inputdates3;\n", " INPUT @6 date1 date7. @14 date2 date9. @24 date3 date11.;\n", " FORMAT date1 weekdate25. \n", " date2 worddate19.\n", " date3 worddatx19.;\n", " DATALINES;\n", " 10Apr08 10Apr2008 10-Apr-2008\n", ";\n", "RUN;\n", " \n", "PROC PRINT data = inputdates3;\n", " TITLE 'The date7 informat and the weekdate and worddate formats';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First, review the INPUT statement and the corresponding forms of the April 10, 2008 date in the DATALINES statement. Note, in particular, that the width of the date informat (7, 9, or 11) tells SAS what form of the date it should expect. Again — SAS will let you know if you misspecify the width of the format!

\n", "

Then, launch and run the SAS program, and review the output so you can appreciate how dates formatted using the weekdate, worddate and worddatx formats are displayed. If the widths that you specify for the these formats are too small, SAS will attempt to abbreviate the date for you. You might want to change the width of the weekdate format to, say, 20 to see this for yourself.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### SAS Date Functions\n", "\n", "The date functions that are available in SAS can be used to:\n", "\n", "* create date values\n", "* take apart date values\n", "* massage date values (what??!)\n", "* calculate intervals\n", "\n", "For no particular reason, we'll look at them in that order.\n", "\n", "#### Using functions to create date values\n", "\n", "The functions that can be used to create date values include:\n", "\n", "* date( ) returns today's date as a SAS date value\n", "* today( ) returns today's date as a SAS date value\n", "* mdy(**m**,**d**,**y**) returns a SAS date value from the given month (m), day (d), and year (y) values\n", "* datejul(**juldate**) converts a Julian date (**juldate**) to a SAS date value\n", "* yyq(**y**, **q**) returns a SAS date value from the given year (**y**) and quarter (**q**) 1, 2, 3, or 4\n", "\n", "The date( ) and today( ) functions are equivalent. That is, they both return the current date as defined as the date on which the SAS program is executed. You don't need to put anything in between the parentheses for those two functions.\n", "\n", "A Julian date is defined in SAS as a date in the form **yyddd** or **yyyyddd**, where **yy** or **yyyy** is a two-digit or four-digit integer that represents the year and **ddd** is the number of the day of the year. The value of ddd must be between 001 and 365 (or 366 for a leap year). So, for example, the SAS Julian date for January 21, 2008 is 2008021.\n", "\n", "Let's look at an example in which these five functions are used." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

The following SAS program creates a temporary SAS data set called createdates that contains six date variables. The variables current1 and current2 are assigned the current date using the date( )and today( ) functions. The variable current3 is assigned the 95th day of the 2008 year using the datejul( ) function. The variables current4 and current5 are assigned the date April 4th, 2008 using the mdy( ) function. And, the variable current6 is assigned the date April 1st, 2008 using the yyq( ) function.

\n", "
" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The createdates data set

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obscurrent1current2current3current4current5current6
126SEP202026SEP202004APR20081762604APR200801APR2008
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA createdates;\n", " current1= date();\n", " current2 = today();\n", " current3 = datejul(2008095);\n", " mon = 4; day = 4; year = 2008;\n", " current4 = mdy(mon, day, year);\n", " current5 = current4;\n", " current6 = yyq(2008, 2);\n", " format current1 current2 current3 current5 current6 date9.;\n", "RUN;\n", " \n", "PROC PRINT data=createdates;\n", " title 'The createdates data set';\n", " var current1 current2 current3 current4 current5 current6;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First, review the program to make sure that you understand how to use each of the five functions. Note, for example, that to tell SAS to determine the SAS date value of the 95th day of the 2008 year, you have to input 2008095 into the datejul( ) function. If you instead input 200895 into the datejul( ) function, SAS reports that you've provided an invalid argument to the datejul( ) function and therefore sets current3 to missing. Also, note that current5 is just the formatted version of the unformatted current4 variable. When you are satisfied that you understand the five functions, launch and run the SAS program. Review the output to convince yourself that createdates does indeed contain the six date variables as described.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Using functions to take apart date values\n", "\n", "The functions that can be used to take apart date values include:\n", "\n", "* day(**date**) returns the day of the month from a SAS date value (**date**)\n", "* month(**date**) returns the month from a SAS date value (**date**)\n", "* year(**date**) returns the year from a SAS date value (**date**)\n", "\n", "The **date** can be specified either as a variable name or as a SAS date constant. Otherwise, fairly self-explanatory! Let's take a look at an example." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

The following SAS program uses the day( ), month( ) and year( ) functions to extract the month, day and year from the wt_date variable:

\n", "
" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The dissected weight dates

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obswt_datewt_mowt_daywt_yr
101DEC20051212005
201DEC20051212005
302DEC20051222005
430NOV200511302005
501JAN2006112006
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA takeapart;\n", " input subj 1-4 l_name $ 18-23 weight 30-32\n", " +1 wt_date mmddyy8. @43 b_date mmddyy8.;\n", " wt_mo = month(wt_date);\n", " wt_day = day(wt_date);\n", " wt_yr = year(wt_date);\n", " format wt_date b_date date9.;\n", " DATALINES;\n", "1024 Alice Smith 1 65 125 12/1/05 01/01/60\n", "1167 Maryann White 1 68 140 12/01/05 01/01/59\n", "1168 Thomas Jones 2 190 12/2/05 06/15/60\n", "1201 Benedictine Arnold 2 68 190 11/30/05 12/31/60\n", "1302 Felicia Ho 1 63 115 1/1/06 06/15/58\n", ";\n", " \n", "RUN;\n", " \n", "PROC PRINT data=takeapart;\n", " title 'The dissected weight dates';\n", " var wt_date wt_mo wt_day wt_yr;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First, review the program to make sure that you understand how to use each of the three functions. Then, launch and run the SAS program, and review the output to convince yourself that the program does as claimed.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Using functions to massage date values\n", "\n", "Okay, here's that section with the intriguing title. The functions that can be used to massage date values include:\n", "\n", "* juldate(**date**) returns the Julian date in yyddd format from a SAS date value (**date**)\n", "* juldate7(**date**) returns the Julian date in yyyyddd format from a SAS date value (**date**)\n", "* qtr(**date**) returns the quarter of the year from a SAS date value (**date**) (1 = first three months, 2 = second three months, 3 = third three months, or 4 = last three months)\n", "* weekday(**date**) returns the number of the day of the week from a date value (**date**) (1 = Sunday, 2 = Monday, ..., and 7 = Saturday)\n", "\n", "Again, the **date** can be specified either as a variable name or as a SAS date constant. And, a Julian date in SAS is defined as a date in the form **yyddd** or **yyyyddd**, where **yy** or **yyyy** is a two-digit or four-digit integer that represents the year and **ddd** is the number of the day of the year (between 001 and 365 (or 366 for a leap year)).\n", "\n", "Let's look at an example in which these four functions are used." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

The following SAS program contains four assignment statements that \"massage\" the wt_date variable. The variable wt_jul1 is assigned the SAS Julian date in yyddd format. The variable wt_jul2 is assigned the SAS Julian date in yyyyddd format. The variable wt_qtr is assigned the quarter in which the wt_date occurs, and the variable wt_day is assigned the weekday on which the wt_date occurs:

\n", "
" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The massaged data set

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obswt_datewt_jul1wt_jul2wt_qtrwt_day
101DEC20055335200533545
201DEC20055335200533545
302DEC20055336200533646
430NOV20055334200533444
501JAN20066001200600111
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA massaged;\n", " input subj 1-4 l_name $ 18-23 weight 30-32\n", " +1 wt_date mmddyy8. @43 b_date mmddyy8.;\n", " wt_jul1 = juldate(wt_date);\n", " wt_jul2 = juldate7(wt_date);\n", " wt_qtr = qtr(wt_date);\n", " wt_day = weekday(wt_date);\n", " format wt_date b_date date9.;\n", " DATALINES;\n", "1024 Alice Smith 1 65 125 12/1/05 01/01/60\n", "1167 Maryann White 1 68 140 12/01/05 01/01/59\n", "1168 Thomas Jones 2 190 12/2/05 06/15/60\n", "1201 Benedictine Arnold 2 68 190 11/30/05 12/31/60\n", "1302 Felicia Ho 1 63 115 1/1/06 06/15/58\n", ";\n", " \n", "RUN;\n", " \n", "PROC PRINT data = massaged;\n", " title 'The massaged data set';\n", " var wt_date wt_jul1 wt_jul2 wt_qtr wt_day;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First, review the program to make sure that you understand how to use each of the four functions. Then, launch and run the SAS program, and review the output to convince yourself that the program does as claimed.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Using functions to calculate intervals\n", "\n", "The functions that can be used to calculate intervals include:\n", "\n", "* yrdif(**startdate**, **enddate**, '**method**') returns the difference in years between two SAS date values (**startdate**, **enddate**) using one of four methods ('**method**')\n", "* datdif(**startdate**, **enddate**, '**method**') returns the difference in days between two SAS date values (**startdate**, **enddate**) using one of four methods ('**method**')\n", "* intck('**interval**', **fromdate**, **todate**) returns the number of time intervals ('**interval**') that occur between two dates (**fromdate**, **todate**)\n", "* intnx('**interval**', **date**, **increment**) applies multiples (**increment**) of a given interval ('**interval**') to a date value (**date**) and returns the resulting value, and hence can be used to identify past or future days, weeks, months, and so on\n", "\n", "We'll take a look at five examples here. The first one uses the yrdif( ) and datdif( ) functions, the next three use the intck( ) function, and the last one uses the intnx( ) function." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

The following SAS program uses the yrdif( ) function to calculate the difference between the subject's birth date (b_date) and first weight date (wt_date1) in order to determine the subject's age. And, the datdif( ) function is used to calculate days, the difference between the subject's first (wt_date1) and second (wt_date2) weight dates:

\n", "
" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The calculation of subject's age

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjb_datewt_date1age
1102401JAN196001DEC200545.9
2116701JAN195901DEC200546.9
3116815JUN196002DEC200545.5
4120131DEC196030NOV200544.9
5130215JUN195801JAN200647.5
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "

The calculation of days between weighings

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjwt_date1wt_date2days
1102401DEC200504MAR200693
2116701DEC200507MAR200696
3116802DEC200530MAR2006118
4120130NOV200527FEB200689
5130201JAN200601APR200690
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA diet;\n", " input subj 1-4 l_name $ 18-23 weight 30-32\n", " +1 wt_date1 mmddyy8. @43 wt_date2 mmddyy8. @52 \n", " b_date mmddyy8.;\n", " age = yrdif(b_date, wt_date1, 'act/act');\n", " days = datdif(wt_date1, wt_date2, 'act/act');\n", " format wt_date1 wt_date2 b_date date9. age 4.1;\n", " DATALINES;\n", "1024 Alice Smith 1 65 125 12/1/05 03/04/06 01/01/60\n", "1167 Maryann White 1 68 140 12/01/05 03/07/06 01/01/59\n", "1168 Thomas Jones 2 190 12/2/05 3/30/06 06/15/60\n", "1201 Benedictine Arnold 2 68 190 11/30/05 2/27/06 12/31/60\n", "1302 Felicia Ho 1 63 115 1/1/06 4/1/06 06/15/58\n", ";\n", "RUN;\n", " \n", "PROC PRINT data=diet;\n", " TITLE \"The calculation of subject's age\";\n", " var subj b_date wt_date1 age;\n", "RUN;\n", " \n", "PROC PRINT data=diet;\n", " TITLE 'The calculation of days between weighings';\n", " var subj wt_date1 wt_date2 days;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Review the assignment statement that is used to calculate the values for the variable age. The first and second arguments of the yrdif( ) function tell SAS, respectively, the start and end date of the desired interval. Here, the start date is b_date and the end date is wt_date1. The third argument of the yrdif( ) function, which must be enclosed in single quotes, tells SAS how to calculate the difference. Here, 'act/act' tells SAS to calculate the difference using the actual number of years between the two dates. The four possible methods in calculating the number of years between two dates using the yrdif( ) function are:

\n", "
    \n", "
  • 'act/act' uses the actual number of days and years between two dates
  • \n", "
  • '30/360' specifies a 30-day month and a 360-day year
  • \n", "
  • 'act/360' uses the actual number of days between dates in calculating the number of years (calculated by the number of days divided by 360)
  • \n", "
  • 'act/365' uses the actual number of days between dates in calculating the number of years (calculated by the number of days divided by 365)
  • \n", "
\n", "

The 'act/act' method is the method that most people would consider to be the most accurate. The other methods are methods that are sometimes used by accountants.

\n", "

Now, review the assignment statement that is used to calculate the values for the variable days. The first and second arguments of the datdif( ) function tell SAS, respectively, the start and end date of the desired interval. Here, the start date is wt_date1 and the end date is wt_date2. The third argument of the datdif( ) function, which must be enclosed in single quotes, tells SAS how to calculate the difference. Here, 'act/act' tells SAS to calculate the difference using the actual number of days between the two dates. The two possible methods in calculating the number of days between two dates using the datdif( ) function are:

\n", "
    \n", "
  • 'act/act' uses the actual number of days and years between two dates
  • \n", "
  • '30/360' specifies a 30-day month and a 360-day year
  • \n", "
\n", "

Again, the 'act/act' method is the method that most people would consider to be the most accurate. The other method is a method that is sometimes used by accountants.

\n", "

When you are satisfied that you understand the two functions, launch and run the SAS program. Review the output to convince yourself that age and days are indeed calculated as described.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

Recall that the intck( ) function returns the number of time intervals, such as the number of days or years, that occur between two dates. The following SAS program is identical to the previous program, except here the subjects' ages at their first weigh-in are determined using both the yrdif( ) and intck( ) functions to get age_yrdif and age_intchk, respectively. Similarly, the numbers of days between the subjects' two weigh-ins are determined using both the datdif( ) and intck( ) functions to get days_datdif and days_intchk, respectively:

\n", "
" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The calculation of subject's age

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjb_datewt_date1age_yrdifage_intck
1102401JAN196001DEC200545.915145
2116701JAN195901DEC200546.915146
3116815JUN196002DEC200545.464345
4120131DEC196030NOV200544.915145
5130215JUN195801JAN200647.547948
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "

The calculation of days between weighings

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjwt_date1wt_date2days_datdifdays_intck
1102401DEC200504MAR20069393
2116701DEC200507MAR20069696
3116802DEC200530MAR2006118118
4120130NOV200527FEB20068989
5130201JAN200601APR20069090
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA diet;\n", " input subj 1-4 l_name $ 18-23 weight 30-32\n", " +1 wt_date1 mmddyy8. @43 wt_date2 mmddyy8. @52 \n", " b_date mmddyy8.;\n", " age_yrdif = yrdif(b_date, wt_date1, 'act/act');\n", " age_intck = intck('year', b_date, wt_date1);\n", " days_datdif = datdif(wt_date1, wt_date2, 'act/act');\n", " days_intck = intck('day', wt_date1, wt_date2);\n", " format wt_date1 wt_date2 b_date date9. age 4.1;\n", " DATALINES;\n", "1024 Alice Smith 1 65 125 12/1/05 03/04/06 01/01/60\n", "1167 Maryann White 1 68 140 12/01/05 03/07/06 01/01/59\n", "1168 Thomas Jones 2 190 12/2/05 3/30/06 06/15/60\n", "1201 Benedictine Arnold 2 68 190 11/30/05 2/27/06 12/31/60\n", "1302 Felicia Ho 1 63 115 1/1/06 4/1/06 06/15/58\n", " ;\n", "RUN;\n", " \n", "PROC PRINT data=diet;\n", " TITLE \"The calculation of subject's age\";\n", " var subj b_date wt_date1 age_yrdif age_intck;\n", "RUN;\n", " \n", "PROC PRINT data=diet;\n", " TITLE 'The calculation of days between weighings';\n", " var subj wt_date1 wt_date2 days_datdif days_intck;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Review the assignment statement that is used to calculate the values for the variable age_intck. The first argument of the intck( ) function, which must appear in single quotes, tells SAS what time interval you are interested in counting. Although there are other intervals available, the most commonly used intervals include 'day', 'weekday', 'week', 'month', 'qtr', and 'year'. The second and third arguments of the intck( ) function tell SAS, respectively, the start and end date of the desired interval. Here, the start date is b_date, the end date is wt_date1, and the time interval is 'year'.

\n", "

Now, review the assignment statement that is used to calculate the values for the variable days_intck. To calculate days, the start date is wt_date1, the end date is wt_date2, and the time interval is 'day'.

\n", "

Theoretically, we should expect the yrdif( ) and intck( ) functions to get the same answers for age, and the datdif( ) and intck( ) functions to get the same answers for days. Launch and run the SAS program, and review the resulting output. Same answers or not? Hmmm ... you should see that the values for days_datdif and days_intck are the same, while the (rounded) values for age_yrdif and age_intck differ.

\n", "

Why is that the case? It has to do with the fact that the intck( ) function counts intervals from fixed interval beginnings, not in multiples of an interval unit from the startdate value. Partial intervals are not counted. For example, 'week' intervals are counted by Sundays rather than seven-day multiples from the startdate value. 'Month' intervals are counted by the first day of each month, and 'year' intervals are counted from January 1st, not in 365-day multiples from the startdate value.

\n", "

The next two examples are intended to help you understand how the intck( ) function counts intervals.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

The following SAS program uses the intck( ) function and SAS date constants to determine the number of days, weeks, months, and years between December 31, 2006 and January 1, 2007. It also calculates the number of years (years2) between January 1, 2007 and December 31, 2007, and the number of years (years3) between January 1, 2007 and January 1, 2008:

\n", "
" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

Time intervals as calculated by intck function

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obsdaysweeksmonthsyearsyears2years3
1101101
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA timeintervals1;\n", " days = intck('day', '31dec2006'd,'01jan2007'd);\n", " weeks = intck('week', '31dec2006'd,'01jan2007'd);\n", " months = intck('month', '31dec2006'd,'01jan2007'd);\n", " years = intck('year', '31dec2006'd,'01jan2007'd);\n", " years2 = intck('year', '01jan2007'd, '31dec2007'd);\n", " years3 = intck('year', '01jan2007'd, '01jan2008'd);\n", "RUN;\n", " \n", "PROC PRINT data = timeintervals1;\n", " TITLE 'Time intervals as calculated by intck function';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First, review the program to make sure that you understand what it is doing. Then, launch and run the SAS program, and review the output. Are you surprised by any of the results? Let me venture to suggest that you find the results for days, weeks, and years3 to make sense, and the results for months, years, and years2 to be a little odd. Let's focus on the three odd results. In spite of only one day passing between 12/31/2006 and 01/01/2007, SAS assigns the variable months the value 1 because between 12/31/2006 and 01/01/2007, exactly one first day of the month is crossed (which happens to be January 1st). Similarly, in spite of only one day passing between 12/31/2006 and 01/01/2007, SAS assigns the variable years the value 1 because between 12/31/2006 and 01/01/2007, exactly one January 1st is crossed. And, in spite of 364 days passing between 01/01/2007 and 12/31/2007, SAS assigns the variable years2 the value 0 because no January 1st is crossed. Now, even though the results for days, weeks, and years3 might make intuitive sense to you, you should still make sure you understand why SAS assigns the values it does here based on how the intck( ) function works.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

In an attempt to explore the intck( ) function further, the following SAS program uses the intck( ) function and SAS date constants to determine the number of days, weeks, weekdays, months, qtrs, and years between March 15, 2007 and March 15, 2008:

\n", "
" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

Time intervals as calculated by intck function

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obsdaysweeksweekdaysmonthsqtrsyears
1366522611241
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA timeintervals2;\n", " days = intck('day', '15mar2007'd,'15mar2008'd);\n", " weeks = intck('week', '15mar2007'd,'15mar2008'd);\n", " weekdays = intck('weekday', '15mar2007'd,'15mar2008'd);\n", " months = intck('month', '15mar2007'd,'15mar2008'd);\n", " qtrs = intck('qtr', '15mar2007'd,'15mar2008'd);\n", " years = intck('year', '15mar2007'd,'15mar2008'd);\n", "RUN;\n", " \n", "PROC PRINT data = timeintervals2;\n", " TITLE 'Time intervals as calculated by intck function';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

The main purpose of this program is to illustrate some of the intervals most commonly used in the intck( ) function. First, review the program to make sure that you understand what it is doing. Then, launch and run the SAS program, and review the output. Are you surprised by any of the results? In each case, I think you'll find the results to make intuitive sense.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

Now, suppose that each subject appearing in the diet data set needs to be weighed again in three months. The following SAS program uses the subject's previous weight date (wt_date) and various versions of the intnx( ) function to determine various versions of each subject's next weight date:

\n", "
" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The data set containing next weight dates

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjwt_datenxdate_b1nxdate_b2nxdate_mnxdate_enxdate_s
1102401DEC200501MAR200601MAR200616MAR200631MAR200601MAR2006
2116701DEC200501MAR200601MAR200616MAR200631MAR200601MAR2006
3116802DEC200501MAR200601MAR200616MAR200631MAR200602MAR2006
4120130NOV200501FEB200601FEB200614FEB200628FEB200628FEB2006
5130201JAN200601APR200601APR200615APR200630APR200601APR2006
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA diet;\n", " input subj 1-4 l_name $ 18-23 weight 30-32\n", " +1 wt_date mmddyy8. @43 b_date mmddyy8.;\n", " nxdate_b1 = intnx('month', wt_date, 3);\n", " nxdate_b2 = intnx('month', wt_date, 3, 'beginning');\n", " nxdate_m = intnx('month', wt_date, 3, 'middle');\n", " nxdate_e = intnx('month', wt_date, 3, 'end');\n", " nxdate_s = intnx('month', wt_date, 3, 'sameday');\n", " format wt_date b_date nxdate_b1 nxdate_b2 \n", " nxdate_m nxdate_e nxdate_s date9.;\n", " DATALINES;\n", "1024 Alice Smith 1 65 125 12/1/05 01/01/60\n", "1167 Maryann White 1 68 140 12/01/05 01/01/59\n", "1168 Thomas Jones 2 190 12/2/05 06/15/60\n", "1201 Benedictine Arnold 2 68 190 11/30/05 12/31/60\n", "1302 Felicia Ho 1 63 115 1/1/06 06/15/58\n", ";\n", "RUN;\n", " \n", "PROC PRINT data=diet;\n", " TITLE 'The data set containing next weight dates';\n", " VAR subj wt_date nxdate_b1 nxdate_b2 \n", " nxdate_m nxdate_e nxdate_s;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Let's review the five assignment statements that calculate five versions of the subjects' next weight dates (nxdate_b1, nxdate_b2, nxdate_m, nxdate_e, and nxdate_s). As you can see, SAS is told to use the 'month' interval in each of the calculations. Again, although there are other intervals available, the most commonly used intervals include 'day', 'weekday', 'week', 'month', 'qtr', and 'year'. SAS is also told to use wt_date as the startdate in each of the calculations. And in each case, SAS is told to advance the wt_date by 3 months. Okay, so the only thing that differs between the five calculations are the last (optional) arguments ('beginning', 'middle', 'end', and 'sameday'). These so-called alignment arguments tell SAS to return either the beginning, middle, or end day of the resulting month. If an alignment is not specified, the beginning day is returned by default. If the 'sameday' alignment is specified, SAS of course returns the same number day but shifted by the number of specified intervals.

\n", "

Let's launch and run the SAS program, and review the output. The dates should be as described. The contents of nxdate_b1 is the same as nxdate_b2, since the beginning day is returned by default. The variable nxdate_m contains the middle day of the resulting month, and nxdate_e contains the end day of the resulting month. And, for four of the subjects, SAS returns the same number day but 3 months in the future. For subject #1201, you would expect SAS to return February 30th, because it is exactly 3 months from November 30th. This illustrates how the intnx( ) function automatically adjusts the date if the resulting date doesn't exist.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### SAS Date System Options\n", "\n", "There are two system options that affect how SAS handles dates —the DATESTYLE= and YEARCUTOFF= options.\n", "\n", "The DATESTYLE= system option tells SAS your intended sequence of month (M), day (D), and year (Y) when dates are ambiguous. Possible settings include MDY, MYD, YMD, YDM, DMY, DYM, and LOCALE. By default, the DATESTYLE system option is set to LOCALE, which tells SAS to use the form of dates that reflect the language and local conventions of the geographical region specified by the LOCALE system option. Yikes, this is sounding circular! Because LOCALE is by default set to ENGLISH for users in the United States, MDY is our default DATESTYLE option. We won't spend any more time on the DATESTYLE system option, but it is something you'll definitely want to know about if you ever get tempted to use the anydtdte. informats to read in dates. (Even though the anydtdte. informats are tempting to use as they allow you to read in different forms of the same date into one date variable, I chose not to present the informat, because I don't like the way it makes SAS have to make decisions about my data!)\n", "\n", "SAS developed the YEARCUTOFF= system option to provide users with a way to handle two digit years. If we specify the date constant '13apr08'd, we could mean 2008, 1908, or even 1808. The YEARCUTOFF = system option eliminates this ambiguity by telling SAS the first year of a 100-year span to be used by date informats and functions when SAS encounters a two-digit year. The default value of YEARCUTOFF is 1920. In the default case, if SAS encounters a two-digit year in your program between 20 and 99, SAS assumes the date has a prefix of 19. And, if SAS encounters a two-digit year in your program between 00 and 19, SAS assumes the date has a prefix of 20. There are two things you can do if you don't like the way SAS is handling your two-digit dates — either use four-digit dates or use the OPTIONS statement to change the default YEARCUTOFF= option. We'll take a look at two examples now just to make sure we understand how SAS handles two-digit years.\n", "\n", "
\n", "

Example

\n", "

The following SAS program uses the default YEARCUTOFF = 1920 to read in nine dates that contain two-digit years ranging from 20 to 99, and then from 00 to 19:

\n", "
" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

Years with two-digits when YEARCUTOFF = 1920

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obsdate1
13 January 1920
23 January 1921
33 January 1949
43 January 1950
53 January 1951
63 January 1999
73 January 2000
83 January 2001
93 January 2019
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "OPTIONS YEARCUTOFF=1920;\n", " \n", "DATA twodigits1920;\n", " INPUT date1 mmddyy8.;\n", " FORMAT date1 worddatx20.;\n", " DATALINES;\n", "01/03/20\n", "01/03/21\n", "01/03/49\n", "01/03/50\n", "01/03/51\n", "01/03/99\n", "01/03/00\n", "01/03/01\n", "01/03/19\n", " ;\n", "RUN;\n", " \n", "PROC PRINT data=twodigits1920;\n", " title 'Years with two-digits when YEARCUTOFF = 1920';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First, review the dates in the DATALINES statement to make sure you understand the range of two-digit years that we are trying to read into the twodigits1920 data set. Then, launch and run the SAS program, and review the resulting output. Note that the dates containing two-digit years between 20 and 99, are displayed as four-digit years between 1920 and 1999. And, the dates containing two-digit years between 00 and 19, are displayed as four-digit years between 2000 and 2019.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Example

\n", "

The following SAS program is identical to the previous program except the YEARCUTOFF= system option has been changed to 1950. As before, SAS reads in nine dates that contain two-digit years ranging from 20 to 99, and then from 00 to 19:

\n", "
" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

Years with two-digits when YEARCUTOFF = 1950

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obsdate1
13 January 2020
23 January 2021
33 January 2049
43 January 1950
53 January 1951
63 January 1999
73 January 2000
83 January 2001
93 January 2019
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "OPTIONS YEARCUTOFF=1950;\n", " \n", "DATA twodigits1950;\n", " INPUT date1 mmddyy8.;\n", " FORMAT date1 worddatx20.;\n", " DATALINES;\n", "01/03/20\n", "01/03/21\n", "01/03/49\n", "01/03/50\n", "01/03/51\n", "01/03/99\n", "01/03/00\n", "01/03/01\n", "01/03/19\n", " ;\n", "RUN;\n", " \n", "PROC PRINT data=twodigits1950;\n", " title 'Years with two-digits when YEARCUTOFF = 1950';\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

Again, review the dates in the DATALINES statement to make sure you understand the range of two-digit years that we are trying to read into the twodigits1950 data set. Then, launch and run the SAS program, and review the resulting output. Note that now the dates containing two-digit years between 50 and 99, are displayed as four-digit years between 1950 and 1999. And, the dates containing two-digit years between 00 and 49, are displayed as four-digit years between 2000 and 2049.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### SAS Time Basics\n", "\n", "We won't spend as much time (no pun intended!) learning how to handle times in SAS as we did learning how to handle dates, but we should still learn the basics. In this section, we'll get a quick and broad overview of the fundamental things you need to know about working with times in SAS. We'll learn how SAS defines time and datetime values, how to use an informat to read a time into a SAS data set, how to use a format to display a SAS time, how to use the most common time functions, and how to define a SAS time constant.\n", "\n", "#### The Definition of a SAS Time and Datetime\n", "\n", "SAS stores time values similar to the way it stores date values. Specifically, SAS stores **time** as a numeric value equal to the number of seconds since midnight. So, for example, SAS stores:\n", "\n", "* a 60 for 12:01 am, , since it is 60 seconds after midnight\n", "* a 95 for 12:01:35 am, since it is 95 seconds after midnight\n", "* a 120 for 12:02 am, since it is 120 seconds after midnight\n", "* and so on ...\n", "\n", "Since there are 86,400 seconds in a day, a SAS time value takes on a value between 0 and 86,400. No matter how you read a time, SAS converts the time to a number as just defined.\n", "\n", "A SAS **datetime** is a special value that combines both date and time values. A SAS datetime value is stored as the number of seconds between midnight on January 1, 1960, and a given date and time. Okay, I don't feel like calculating one of these datetimes out myself. I'll trust the SAS manual that I'm looking at that tells me, for example, that the SAS datetime for April 22, 1989 at 4:10:45 pm equals 92,488,384 seconds. I guess that if you need the added accuracy of working with seconds, then datetimes are for you. I personally have never needed to use them.\n", "\n", "#### Using Informats and Formats to Input and Display a SAS Time\n", "\n", "Just as we need to tell SAS what form a date should take, we need to tell SAS what form a time should take. As you'd probably expect, we use **time informats** in an INPUT statement to tell SAS the form of the times to be read in. And, we use **time formats** in a FORMAT statement to tell SAS the form of the times to be displayed.\n", "\n", "
\n", "

Example

\n", "

The following SAS program reads five observations into a SAS data set called diet. One of the variables — weight time (wt_time) — is in hh:mm:ss format, and therefore SAS is told to read the dates using the time8. informat:

\n", "
" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The diet data set with formatted weight times

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjwt_timewtm_fmt1wtm_fmt2wtm_fmt3
11024600:010.020:01:00
211679000:150.250:15:00
311684320012:0012.0012:00:00
4120100:000.000:00:00
513028639924:0024.0023:59:59
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA diet;\n", " input subj 1-4 l_name $ 18-23 weight 30-32\n", " +1 wt_date mmddyy8. @43 b_date mmddyy8.\n", " @52 wt_time time8.;\n", " wtm_fmt1 = wt_time;\n", " wtm_fmt2 = wt_time;\n", " wtm_fmt3 = wt_time;\n", " format wtm_fmt1 hhmm.\n", " wtm_fmt2 hour5.2\n", " wtm_fmt3 time8.;\n", " DATALINES;\n", "1024 Alice Smith 1 65 125 12/1/05 01/01/60 00:01:00\n", "1167 Maryann White 1 68 140 12/01/05 01/01/59 00:15:00\n", "1168 Thomas Jones 2 190 12/2/05 06/15/60 12:00:00\n", "1201 Benedictine Arnold 2 68 190 11/30/05 12/31/60 00:00:00\n", "1302 Felicia Ho 1 63 115 1/1/06 06/15/58 23:59:59\n", ";\n", "RUN;\n", " \n", "PROC PRINT data=diet;\n", " title 'The diet data set with formatted weight times';\n", " var subj wt_time wtm_fmt1 wtm_fmt2 wtm_fmt3;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First, review the program so that you understand what it is doing. Specifically, pay attention to the time8. informat used to read in the wt_time variable. Also, note that three new weight time variables — wtm_fmt1, wtm_fmt2, wtm_fmt3 — are assigned to equal the values of the wt_time variable. The three new variables are each formatted differently, however. The FORMAT statement tells SAS to format wtm_fmt1 as hhmm., wtm_fmt2 as hour5.2, and wtm_fmt3 as time8.

\n", "

Now, launch and run the SAS program, and review the resulting output to familiarize yourself with the contents of the diet data set. Note, in particular, the numeric values that are stored for the unformatted wt_time variable. As expected, the 00:01:00 time is stored as a 60, the 00:00:00 time is stored as a 0, and the 00:15:00 time is stored as a 900. Then, note the formatted versions of the weight time variables. As you can see, the hhmm. format displays the time on a 24-hour clock. The hour5.2 format displays the time as hours and decimal fractions of hours. And, the time8. format displays the time as hours, minutes and seconds in the form hh:mm:ss.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Using SAS Time Functions\n", "\n", "Just as is the case for SAS dates, the best thing about SAS times is that, because SAS time values are numeric values, you can easily sort them, subtract them, and add them. You can also compare times. Or, you can use them in any of the available time functions. The most commonly used time functions are:\n", "\n", "* time( ) returns the current time as a SAS time value\n", "* hms(**h**, **m**, **s**) returns a SAS time value for the given hour (**h**), minutes (**m**), and seconds (**s**)\n", "* hour(**time**) returns the hour portion of a SAS time value (**time**)\n", "* minute(**time**) returns the minute portion of a SAS time value (**time**)\n", "* second(**time**) returns the second portion of a SAS time value (**time**)\n", "\n", "We won't look at an example of their use here, but the interval functions intnx( ) and intck( ) that we explored on SAS dates can also be used on SAS times.\n", "\n", "
\n", "

Example

\n", "

The following SAS program illustrates the use of the five time functions mentioned above. Specifically, the variable curtime is assigned the current time using the time( ) function. Then, the hour( ), minute( ) and second( ) functions are used to extract the hours, minutes and seconds from the wt_time variable. And finally, the hms( ) function is used to put the hours, minutes, and seconds back together again to create a new variable called wt_time2 that equals the old wt_time variable:

\n", "
" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The diet data set with five new variables

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjcurtimewt_timewt_hrwt_minwt_secwt_time2
110248:11:320:01:000100:01:00
211678:11:320:15:0001500:15:00
311688:11:3212:00:00120012:00:00
412018:11:320:00:000000:00:00
513028:11:3223:59:5923595923:59:59
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA diet;\n", " input subj 1-4 l_name $ 18-23 weight 30-32\n", " +1 wt_date mmddyy8. @43 b_date mmddyy8.\n", " @52 wt_time time8.;\n", " curtime = time();\n", " wt_hr = hour(wt_time);\n", " wt_min = minute(wt_time);\n", " wt_sec = second(wt_time);\n", " wt_time2 = hms(wt_hr, wt_min, wt_sec);\n", " format curtime wt_time wt_time2 time8.;\n", " DATALINES;\n", "1024 Alice Smith 1 65 125 12/1/05 01/01/60 00:01:00\n", "1167 Maryann White 1 68 140 12/01/05 01/01/59 00:15:00\n", "1168 Thomas Jones 2 190 12/2/05 06/15/60 12:00:00\n", "1201 Benedictine Arnold 2 68 190 11/30/05 12/31/60 00:00:00\n", "1302 Felicia Ho 1 63 115 1/1/06 06/15/58 23:59:59\n", ";\n", "RUN;\n", " \n", "PROC PRINT data=diet;\n", " title 'The diet data set with five new variables';\n", " var subj curtime wt_time wt_hr wt_min wt_sec wt_time2;\n", "RUN;" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First, review the program to make sure that you understand how to use each of the five functions. Then, launch and run the SAS program, and review the output to convince yourself that the program does as claimed.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Comparing Times\n", "\n", "Again, because SAS time values are numeric values, you can easily compare two or more times The comparisons are made just as the comparisons between any two numbers would take place. For example, because the time 00:10:00 is stored as a 600 in SAS, it is considered smaller than the time 00:15:00, which is stored as a 900 in SAS.\n", "\n", "
\n", "

Example

\n", "

The following SAS program illustrates how to compare the values of a time variable, not to the values of some other time variable, but rather to a time constant. Specifically, the WHERE= option on the DATA statement tells SAS to output to the diet data set only those individuals whose wt_time is between midnight and noon, inclusive:

\n", "
" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "SAS Output\n", "\n", "\n", "\n", "
\n", "
\n", "

The subsetted diet data set

\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Obssubjl_namewt_timetime_int
11024Smith0:01:005.0
21167White0:15:004.8
31168Jones12:00:007.0
41201Arnold0:00:005.0
\n", "
\n", "
\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "DATA diet (where = ((wt_time ge '00:00:00't) \n", " and (wt_time le '12:00:00't)));;\n", " input subj 1-4 l_name $ 18-23 weight 30-32\n", " +1 wt_date mmddyy8. @43 b_date mmddyy8.\n", " @52 wt_time time8.;\n", " time_int = abs((wt_time - '05:00:00't)/3600);\n", " format wt_time time8. time_int 4.1;\n", "DATALINES;\n", "1024 Alice Smith 1 65 125 12/1/05 01/01/60 00:01:00\n", "1167 Maryann White 1 68 140 12/01/05 01/01/59 00:15:00\n", "1168 Thomas Jones 2 190 12/2/05 06/15/60 12:00:00\n", "1201 Benedictine Arnold 2 68 190 11/30/05 12/31/60 00:00:00\n", "1302 Felicia Ho 1 63 115 1/1/06 06/15/58 23:59:59\n", "; \n", "RUN;\n", " \n", "PROC PRINT data=diet;\n", " title 'The subsetted diet data set';\n", " var subj l_name wt_time time_int;\n", "RUN" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

First, review the program to make sure you understand what it is doing. Note, for example, the form of the SAS time constants:

\n", "

'00:00:00't

\n", "

and

\n", "

'12:00:00't

\n", "

used in the WHERE= option. In general, a SAS time constant takes the form 'hh:mm:ss't where hh is the hour in 24-hour time, mm is the minutes, and ss (optional) are the seconds. The letter t that follows the time in single quotes tells SAS to treat the time string like a constant. Note that regardless of how you have informatted or formatted your SAS times, the SAS time constant always takes the above form.

\n", "

This program also illustrates how you can use SAS time variables easily in calculations. The variable time_int is assigned the absolute difference in time, in hours, between each individual's weight time and their expected weight time, say for example, 5 am.

\n", "

Now, launch and run the SAS program. Then, review the resulting output to convince yourself that only those individuals whose weight time is between midnight and noon are included in the output diet data set.

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercises\n", "\n", "We will use the dataset Bike_Lanes.csv. Please download it from the course webiste.\n", "\n", "1. Use proc freq to make a table of the different bike lane types.\n", "2. Create a format that changes changes the bike lane types by mapping \"SIDEPATH\", \"BIKE BOULEVARD\", and \"BIKE LANE\" to itself and all others to \" \". Apply this format to type and make a table of type using PROC FREQ. What happens to the other bike lane types?\n", "3. Create a format that changes the bike lane types to be \"CONTRAFLOW\", \"SHARED BUS BIKE\", \"SHARROW\", \"SIGNED ROUTE\", or \"OTHER\" if the lane type is anything else. Apply this format to type and create a frequency table with PROC FREQ to see the result of the translation.\n", "4. Write a datatep that can be used to read in the following small dataset with three dates and one time. Then print the dataset using readable date formats. Print out the dataset using DATE and TIME formats to confirm that the data was properly read in (see the SAS documentation pages as needed for DATE and TIME informats/formats).\n", "
\n",
    "\n",
    "DATA temp;\n",
    "  INPUT date1 /*informat1*/ +1 date2 /*informat2*/ +1\n",
    "        date3 /*informat3*/ @32 time /*informat4*/;\n",
    "  DATALINES;\n",
    "2014/02/14 06Jan2018 4/5/2016   03:2:22\n",
    ";\n",
    "RUN;\n",
    "\n",
    "
\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "SAS", "language": "sas", "name": "sas" }, "language_info": { "codemirror_mode": "sas", "file_extension": ".sas", "mimetype": "text/x-sas", "name": "sas" } }, "nbformat": 4, "nbformat_minor": 2 }