Vous êtes sur la page 1sur 62

Lezione 1: Overview di SAS, i data sets, la libname, sintassi SAS

COSE SAS?
SAS un pacchetto statistico molto potente e strutturato composto da pi pacchetti

LA STRUTTURA
Quelli trattati nel corso:
SAS\BASE Procedure e passi base SAS\STAT Per le elaborazioni Statistiche SAS\GRAPH Per la produzione di Grafici

COSA PUOI FARE CON SAS?

L INTERFACCIA
Come la maggior parte dei sistemi SAS formato dal programma e dallinterfaccia.
Linterfaccia costituita da tre principali finestre:
PROGRAM EDITOR OUTPUT LOG In aggiunta alle tre finestre linterfaccia composta da diversi men a tendina che permettono di accedere alle varie funzionalit del programma.

Finestra LOG

Librerie dei Dati

Finestra EDITOR

Finestra OUTPUT

FINESTRE PRINCIPALI - EDITOR


NellEDITOR vengono definite le istruzioni che comporranno il programma. Istruzioni che devono seguire linsieme delle regole del linguaggio SAS, ovvero la sintassi del linguaggio. Le istruzioni vengono eseguite attraverso il comando run (richiamabile attraverso i tasti F3 e F8 della tastiera). Le istruzioni vengono eseguite nellordine in cui sono state definite nelleditor. Una volte eseguite le istruzioni possibile consultare la finestra OUTPUT per visualizzare gli eventuali risultati delle procedure, e la finestra LOG per verificare che il codice lanciato non abbia causato errori.

Esegue il programma (F3 o F8)

Nuovo editor

Navigazione nelle librerie di dati

FINESTRE PRINCIPALI - OUTPUT


NellOUTPUT vengono visualizzati i risultati visivi delle procedure e delle istruzioni eseguite dal programma. Ad esempio il contenuto di un dateset o il risultato di una procedura. Nellesempio viene stampato nelloutput parte del contenuto presente nel dataset CARS della libreria di dafault SASHELP.

FINESTRE PRINCIPALI - LOG


Nella finestra LOG vengono visualizzate informazioni sullelaborazione, ossia segnalazioni di errore nella scrittura della sintassi, il nome degli archivi di dati che si stanno utilizzando o il numero di osservazioni che si processano.

In caso di errori durante lesecuzione del programma nel log compariranno messaggi di errore o segnalazioni che segnalano anomalie: ogni volta che si fa girare un programma consigliabile controllare nella finestra di LOG la comparsa di eventuali messaggi:
I pi importanti sono: ERROR WARNING

Esempio di errore: si vuole stampare una variabile non presente nel dataset.
NB. Compare in rosso la scritta ERROR nella finestra LOG

UN PROGRAMMA SAS

IL DATA STEP
I passi di data servono per lacquisizione di dati da un archivio o per la creazione di tabelle di dati (DATASET).

LE PROCEDURE
sono di diverso tipo e possono servire per:
Eseguire lanalisi dei dati. Acquisire dati da formati diversi da quello SAS (dataset). Stampare/visualizzare i dati o i risultati di altre procedure.

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

SAS Libraries
SAS data sets are stored in SAS libraries. A SAS library is a collection of SAS files that are referenced and stored as a unit.

Each file is a member of the library.


13

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

SAS Libraries
You can think of a SAS library as a drawer in a filing cabinet and a SAS data set as one of the files in the drawer.

data set

libraries

14
14

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

How SAS Libraries Are Defined


When a SAS session starts, SAS automatically creates one temporary and at least one permanent SAS library that you can access. These libraries are open and ready to be used.

temporary library permanent library

work
sashelp

15
15

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

Assigning a Libref
Regardless of the operating system that you use, you refer to a SAS library by a logical name called a library reference name, or libref.

work
libref sashelp

A libref is a shortcut to the library.

16
16

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

Temporary Library
Work is a temporary library where you can store and access SAS data sets for the duration of the SAS session. It is the default library.

work

SAS deletes the work library and its contents when the session terminates.
17

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

Permanent Libraries
Sashelp is a permanent library that contains sample SAS data sets you can access during your SAS session.

sashelp

18

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

Permanent Libraries
Sasuser is a permanent library that you can use to store and access SAS data sets in any SAS session.

sasuser

SAS data sets in permanent libraries are saved after your SAS session terminates.
19

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

Accessing SAS Data Sets


All SAS data sets have a two-level name that consists of the libref and the data set name, separated by a period.
libref data set name

work.newsalesemps sashelp.class
libref data set name

libref.data-set-name

When a data set is in the temporary work library, you can use a one-level name (for example, newsalesemps).
20

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

User-Defined Libraries
Users can create their own SAS libraries. A user-defined library is permanent. Data sets are stored until the user deletes them. is implemented within the operating environments file system. is not automatically available in a SAS session.

21
21

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

User-Defined Libraries
Operating Environment Microsoft Windows UNIX z/OS (OS/390) A SAS library is Example

A folder A directory A sequential file

s:\workshop ~/workshop userid.workshop.sasdata

The user must assign a libref to the user-defined library to make it available in a SAS session.

22
22

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

Accessing a Permanent Library


Step 2 Use a SAS LIBNAME statement to associate the libref with the physical location of the library.

libref Data

Associate the libref orion with the Windows folder so that it is available to your SAS session.
23

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

LIBNAME Statement
The SAS LIBNAME statement is a global SAS statement.
libname Data"s:\workshop"; LIBNAME libref "SAS-library" <options>;

It is not required to be in a DATA step or PROC step. It does not require a RUN statement. It executes immediately. It remains in effect until changed or canceled, or until the session ends. Use the location of your course data in your LIBNAME statement.

24

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

Viewing the Log


Partial SAS Log
47 libname orion "s:\workshop"; NOTE: Libref ORION was successfully assigned as follows: Engine: V9 Physical Name: s:\workshop

25

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

3.04 Multiple Choice Poll


Which of the following correctly assigns the libref myfiles to a SAS library in the c:\mysasfiles folder?

a. libname orion myfiles "c:\mysasfiles"; b. libname myfiles "c:\mysasfiles"; c. libref orion myfiles "c:\mysasfiles"; d. libref myfiles "c:\mysasfiles";

26

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

3.04 Multiple Choice Poll Correct Answer


Which of the following correctly assigns the libref myfiles to a SAS library in the c:\mysasfiles folder?

a. libname orion myfiles "c:\mysasfiles"; b. libname myfiles "c:\mysasfiles"; c. libref orion myfiles "c:\mysasfiles"; d. libref myfiles "c:\mysasfiles";

27

Libreria permanente:
data dati.esempio; set esempio; run;

Libreria temporanea:
data work.esempio; set esempio; run; data esempio2; set esempio; run;

Il nome della libreria temporanea (work) si pu omettere

I DATASET
What Is a SAS Data Set?

A SAS data set is a specially structured data file that SAS creates and that only SAS can read. A SAS data set is a table that contains observations and variables.
observations

variables

I DATASET SAS Data Set Terminology


SAS Terminology SAS Data Set Database Terminology Table

Observation
Variable

Row
Column

I DATASET
Per creare un nuovo dataset basandosi su dati esterni si utilizzano delle procedure di importazione di dati che vedremo in seguito. Per creare un nuovo dataset basandosi su uno gi esistente si usa il comando SET.

Usando il comando set si ottiene un nuovo dataset con le stesse variabili e le stesse osservazioni del dataset base. Nel nuovo dataset si potranno poi creare nuove variabili e nuove osservazioni.
data a; set dati.esempio; nuovaVar=altezza*2; run; Con questo codice si creer un nuovo dataset (a) con le stesse variabili e osservazioni del dataset esempio della libreria dati. Viene inoltre creata nel nuovo dataset una nuova variabile (nuovaVar) che avr come valore il valore della variabile altezza (presente nel dataset dati.esempio) moltiplicato per 2. Questa variabile non verr creata nel dataset di partenza (dati.esempio).

DATASET PERMANENTI E TEMPORANEI


I Dataset sono suddivisi in due categorie:
TEMPORANEE PERMANENTI

In default i dataset creati da SAS vengono salvati nella libreria temporanea WORK. I dataset creati in librerie temporanee vengono cancellati alla fine della sessione SAS, quindi verranno persi quando si arresta SAS.
Per ovviare a questo problema possibile creare delle librerie permanenti, associate a un nome logico, in cui possibile salvare i propri dati al fine di averli disponibili allavvio di una nuova sessione di SAS. Per definire una libreria permanente necessario usare listruzione libname, che permette di associare al nome di una libreria il percorso di una cartella dove verranno salvati i dati SAS.

LISTRUZIONE SET
Con listruzione SET possibile anche aggiungere a un dataset le osservazioni (record) derivanti da un altro. Ad esempio: data a; set dati.esempio1 dati.esempio2; run; Per poter usare in modo efficace il comando SET i nomi delle variabili dei due dataset che si vogliono appendere devono essere uguali.

LISTRUZIONE SET
data a; set dati.esempio1; run;
data b; set dati.esempio2; run; data c; set a b; run; Il dataset A ha 2 osservazioni e 3 variabili. Il dataset B ha 2 osservazioni e 3 variabili. Il dataset C, ottenuto con il comando set di A e B ha 4 osservazioni e 3 variabili. Per le variabili presenti in uno solo dei dataset vengono creati valori mancanti per le osservazioni provenienti dal dataset in cui la variabile stessa non era presente.

LA VISUALIZZAZIONE DEI DATASET


La visualizzazione dei dataset avviene attraverso la navigazione nelle librerie di dati. Aprendo il dateset si vedranno tutti i dati e tutte le variabili presenti in esso.
Modalit di modifica dei dati Nome della libreria Modalit di visualizzazione dei dati

Dataset

LA VISUALIZZAZIONE DEI DATASET


Una volta visualizzato il dataset, possibile visualizzare tutte le informazioni riguardante esso:
Il numero di osservazioni; Il numero di variabili; Ad ogni osservazione assegnato un numero progressivo, che permette di identificarla in maniera univoca allinterno del dataset; Per ogni variabile possibile visualizzare:
il tipo (caratteriale o numerico); il formato applicato, che va a modificare la visualizzazione del contenuto per quella variabile; la label, ovvero la stringa che viene visualizzata come intestazione della variabile;

SINTASSI

SINTASSI
Alcune regole generali riguardo la sintassi SAS:
Ogni istruzione o comando finisce sempre con il punto e virgola (;). Il linguaggio SAS non distingue lettere maiuscole e minuscole nei comandi (Non CASE SENSITIVE) Diverse istruzioni possono essere scritte sulla stessa riga, ma devono essere sempre separate dal <;>. Si possono inserire commenti nel codice del programma, il testo del commento deve essere compreso fra </*> e <*/>. I nomi delle variabili e dei dataset possono contenere lettere, numeri o lunderscore (_), ma il primo carattere pu essere solo una lettera o lunderscore.

SYNTAX ERRORS
A syntax error is an error in the spelling or grammar of a SAS statement. SAS finds syntax errors as it compiles each SAS statement, before execution begins.

Examples of syntax errors:


misspelled keywords unmatched quotation marks missing semicolons invalid options

40

Quiz
daat work.newsalesemps; length First_Name $ 12 $ 18 Job_Title $ 25; One is anLast_Name invalid option. What are the infile "&path\newemps.csv" dlm=','; two syntax errors?$ Last_Name $ input First_Name Job_Title $ Salary; run; proc print data=work.newsalesemps run;

This program includes three syntax errors. other

41

p102d04

Quiz Correct Answer


misspelled daat work.newsalesemps; length keyword First_Name $ 12 $ option. 18 Job_Title 25;the other One is Last_Name an invalid What$are infile "&path\newemps.csv" dlm=','; two syntax errors? input First_Name $ Last_Name $ Job_Title $ Salary; missing run; semicolon
proc print data=work.newsalesemps run;

This program includes three syntax errors.

42

p102d04

Syntax Errors
The Enhanced Editor in SAS and the Program Editor in SAS Enterprise Guide use the color red to indicate a potential error in your SAS code.

43

Syntax Errors
When SAS encounters a syntax error, it writes a warning or error message to the log.
ERROR 22-322: Syntax error, expecting one of the following: a name, a quoted string, (, /, ;, _DATA_, _LAST_, _NULL_.

WARNING: Data set WORK.TEST was not replaced because this step was stopped.

You should always check the log to make sure that the program ran successfully, even if output is generated.
44

Quiz
What is the syntax error in this program?

p102d05

Quiz Correct Answer


What is the syntax error in this program?

The program contains unbalanced quotation marks in the DLM= option in the INFILE statement.
p102d05

LACQUISIZIONE DI DATI
SAS in grado di lavorare su grandi quantit di dati, a patto che questi siano in un formato comprensibile per SAS (dalla versione 7 di SAS e per le successive formato .sas7bdat)
Quindi, al fine di poter lavorare sui dati necessario trasformare i dati di origine in formato ASCII in tipi di file utili a SAS.

I file ASCII per acquisire i dati possono essere suddivisi in due gruppi
Dati in formato libero Dati in formato colonna

LACQUISIZIONE DI DATI
Per lacquisizione di dati da file ASCII i comandi principali sono INFILE e INPUT. Il comando INFILE permette di specificare il nome e il percorso del file contenente i dati da acquisire. Il comando INPUT permette di definire la struttura del file, ovvero il nome e il numero di variabili e il loro formato (caratteriale o numerico). Il modo in cui vengono definite le variabili allinterno del comando varia a seconda del file che bisogner importare, ovvero in formato libero o in formato colonna

LACQUISIZIONE DI DATI
Per acquisire un file di tipo ASCII il passo di data composto da 4 comandi principali:
DATA: inizia il datastep. Definisce il nome del dataset e leventuale libreria in cui sar salvato. INFILE: specifica il nome del file da acquisire. INPUT: descrive la struttura del file e quindi il nome e il tipo di varibili. Per le variabili caratteriali il nome seguito dal simbolo <$>. RUN: conclusione del passo di data.

QUIZ

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

1. How many step boundaries does this program contain?


a. b. c. d. data work.staff; four length First_Name $ 12 five Last_Name $ 18 six Job_Title $ 25; infile "&path\newemployees.csv" seven dlm=','; input First_Name $ Last_Name$ Job_Title $ Salary; run; proc print data=work.staff; run;

proc means data=work.staff; var Salary; run;


52

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

1. How many step boundaries does this program contain?


a. b. c. d. data work.staff; four length First_Name $ 12 five Last_Name $ 18 six Job_Title $ 25; infile "&path\newemployees.csv" seven dlm=','; input First_Name $ Last_Name$ Job_Title $ Salary; run; proc print data=work.staff; run;

proc means data=work.staff; var Salary; run;


53

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

2. Which of the following is a SAS syntax requirement?


a. b. c. d. e. Begin each statement in column one. Put only one statement on each line. Separate each step with a line space. End each statement with a semicolon. Put a RUN statement after every DATA or PROC step.

54

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

2. Which of the following is a SAS syntax requirement?


a. b. c. d. e. Begin each statement in column one. Put only one statement on each line. Separate each step with a line space. End each statement with a semicolon. Put a RUN statement after every DATA or PROC step.

55

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

3. Which of the following steps is typically used to generate reports and graphs?
a. b. c. d. DATA PROC REPORT RUN

56

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

3. Which of the following steps is typically used to generate reports and graphs?
a. b. c. d. DATA PROC REPORT RUN

57

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

4. Does this comment contain syntax errors?


/* Report created for budget presentation; revised October 15. */ proc print data=work.newloan; run;

a. No. The comment is correctly specified. b. Yes. Every comment line must end with a semicolon. c. Yes. The comment text incorrectly begins on line one. d. Yes. The comment contains a semicolon, which causes an error message.
58

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

4. Does this comment contain syntax errors?


/* Report created for budget presentation; revised October 15. */ proc print data=work.newloan; run;

a. No. The comment is correctly specified. b. Yes. Every comment line must end with a semicolon. c. Yes. The comment text incorrectly begins on line one. d. Yes. The comment contains a semicolon, which causes an error message.
59

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

5. What result would you expect from submitting this step?


proc print data=work.newsalesemps run; a. an HTML report of the work.newsalesemps data set b. an error message in the log c. a LISTING report of the work.newsalesemps data set d. the creation of the temporary data set work.newsalesemps

60

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

5. What result would you expect from submitting this step?


proc print data=work.newsalesemps run; a. an HTML report of the work.newsalesemps data set b. an error message in the log c. a LISTING report of the work.newsalesemps data set d. the creation of the temporary data set work.newsalesemps

61

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

6. Suppose you submit a short, simple DATA step. If the active window displays the message DATA step running for a long time, what probably happened? a. You misspelled a keyword. b. You forgot to end the DATA step with a RUN statement. c. You specified an invalid data set option. d. Some data values were not appropriate for the SAS statements that you specified.

62

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

6. Suppose you submit a short, simple DATA step. If the active window displays the message DATA step running for a long time, what probably happened? a. You misspelled a keyword. b. You forgot to end the DATA step with a RUN statement. c. You specified an invalid data set option. d. Some data values were not appropriate for the SAS statements that you specified.

63

C op yr i g h t 2 0 1 2 , S A S I n s t i t u t e I n c . A l l r i g h t s r es er v e d .

Missing Data Values


Missing values are valid values in a SAS data set. Partial work.newsalesemps
First_Name Monica Kevin Petrea Last_Name Kletschkus Lyon Soltau Job_Title Sales Rep. IV Sales Rep. I Salary . 26955 27440

A blank represents a missing character value.

A period represents a missing numeric value.

A value must exist for every variable in every observation.


64
64

Vous aimerez peut-être aussi