Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
UNIVERSITÀ DI GENOVA
Via Dodecaneso, 35 - 16146 GENOVA (Italy)
tel. +39-010-3536751 fax +39-010-3536752
NOTE INTRODUTTIVE AL
SISTEMA SAS
3
J. Approfondimenti: manipolazione di Data Set SAS
J1. Overview of Methods for Combining SAS Data Sets
J2. Manipolazione di Data Set SAS
J2.1 Per concatenare i DSS: uso di Set
J2.2 Per concatenare i DSS: uso di Set – by e di Merge – by
J2.3 Per affiancare DSS con variabili diverse: uso di Set – Set e di Merge
J2.4 Per aggiornare un DSS: uso di Update e di Merge – by
J2.5 Per aggingere osservazioni a un DSS: la proc Append
J3. Osservazioni ripetute: uso di Set – by e variabili first.<..> e last.<..>
K. Approfondimenti: lettura di dati grezzi
K1. Input a lista con formato
K2. Input con nome
K3. Sospensione dell’input: uso di @
K4. Opzioni di Infile per leggere dati con delimitatori nell’input a lista
L. Approfondimenti: formati di lettura e scrittura dei dati
L1. Istruzione Format
L2. Istruzione Informat
L3. Istruzione Lenght
L4. Istruzione Atttrib
L5. La Proc Format
L5.1 Istruzione Value
L5.2 Istruzione Invalue
L5.3 Istruzione Picture
L5.4 Alcuni esempi di cambio di formati
L5.5 Funzioni di conversione da variabile carattere a numerica e viceversa
L6. SAS Date, Time, and Datetime Values
L7. Alcune funzioni di arrotondamento
L8. Alcune funzioni sulle variabili carattere
M. Approfondimenti: le Macro SAS
M1. Introduzione alla programmazione con macro
M2. SAS Macro Language: Reference
N. Approfondimenti: come operare con matrici in SAS
4
A. Aspetti generali
A1. IL LINGUAGGIO SAS
Il SAS è un sistema software che fornisce strumenti necessari per analizzare dati. E' composto da:
- un linguaggio usato per la manipolazione dei dati;
- una libreria di procedure pre-confezionate per uso generale.
Esiste un modulo SAS BASE più vari moduli per particolari applicazioni quali ad esempio:
- statistica (STAT)
- controllo qualità (QC)
- ricerca operativa (OR)
- serie temporali (TSA)
- manipolazione matrici (IML)
- grafica avanzata (GRAPH)
- gestione risorse calcolatore
- gestione Data Base.
5
A4. I DATA SET DI TIPO SAS
osservazioni
ESEMPIO:
Le colonne sono chiamate variabili; ciascuna di esse ha un nome (si consiglia di assegnare sempre
nomi mnemonici). Un nome deve seguire le seguenti regole sintattiche:
a) deve essere formato da 1 a 8 caratteri;
b) può contenere cifre al suo interno;
Osservazione: un DATA SET SAS non è un file di dati tradizionale ma è leggibile solo con il software
con cui è stato costruito.
Ogni file SAS ha un nome. I nomi dei file seguono le stesse regole dei nomi delle variabili.
La lunghezza massima del nome di una variabile (salvo diversa dichiarazione) è di 8 caratteri .
Le variabili assumono valori che dipendono dalla elaborazione che si sta effettuando.
In particolari situazioni non esistono valori associabili ad una variabile (sia in fase di INPUT dei
dati, sia a causa di operazioni su dati "invalidi"); in questo caso il SAS associa un particolare valore alla
variabile, definito "valore mancante" o "valore vuoto" o "missing value".
Il SAS esegue automaticamente la conversione da variabile carattere a numerica quando:
- una variabile carattere è assegnata ad una variabile numerica definita precedentemente;
- si esegue il confronto tra una variabile carattere e una numerica;
- si eseguono operazioni aritmetiche su variabili carattere (solo nel caso in cui siano formate da cifre).
6
B. COME ESEGUIRE UN PROGRAMMA CON IL
SAS PER WINDOWS
Avviando il SAS da Windows compare una schermata composta generalmente da due finestre: una
di Log e l'altra di Program Editor. Un'altra finestra, quella di Output si apre quando il
programma crea un output non grafico
Alcune osservazioni sulla scrittura e l'esecuzione dei programmi:
- il testo del programma va scritto nella finestra di Program Editor
- per salvare il programma su disco: dalla finestra di Program Editor, dal menù File si seleziona:
Save o Save as
Con Save il programma (dopo il primo salvataggio) è salvato con il nome dell'ultimo programma
richiamato (fare attenzione). Il nome di un programma salvato compare nell'intestazione della finestra
di Program Editor.
- per richiamare un programma salvato in precedenza in un file: dalla finestra di Program Editor,
dal menù File si seleziona:
Open --> Read File
- per far eseguire programma occorre dalla finestra di P.E., dal menù Local selezionare:
Submit (che corrisponde al tasto funzionale F8)
- ad ogni esecuzione il testo del programma scompare dalla finestra del Program Editor, ma può
essere richiamato selezionando dalla finestra di Program Editor, dal menù Local:
Recall (corrispondente al tasto funzionale F4)
con Recall si richiama l'ultimo programma eseguito (se si ripete l'operazione due volte vengono
richiamati gli ultimi due programmi eseguiti, e così via)
- mentre il programma viene eseguito nella finestra di Log compaiono le indicazioni di ciò che il
programma sta facendo come, ad esempio, tempi di esecuzione delle procedure, eventuali errori,
numero di osservazioni lette nel Data Set, ecc.
- se è previsto un output non grafico questo viene scritto nella finestra di Output
- avendo le finestre un'estensione limitata, non sempre tutto il loro contenuto è visibile. Per scorrere
all'interno di una finestra si eseguono le solite operazioni delle applicazioni Windows
- per spostarsi da una finestra all'altra si può utilizare il menù Window o il mouse o usare i tasti
funzionali:
- F5 per la finestra di Program Editor
- F6 per la finestra di Log
- F7 per la finestra di Output
- i comandi di edizione di testo si trovano nel menu Edit
- per rimuovere il contenuto di tutte le linee di testo da qualsiasi finestra, dal menù Edit selezionare:
Clear text (corrispondente ai tasti control+e)
- per conservare i risultati contenuti nella finestra di Log e di Output in un file permanente si usa il
comando Save come per il salvataggio di un programma
- per conoscere il contenuto dei tasti funzionali bisogna, dal menù Help selezionare:
Keys
con tale operazione compare una finestra Keys con le indicazioni volute
- nel menù Help, selezionando
SAS System
si possono trovare la sintassi e le spiegazioni per le varie procedure e per l'uso dei comandi SAS
7
C. ESEMPI DI PROGRAMMA SAS
C1 PRIMO ESEMPIO
PROGRAMMA SAS n. 1:
DATA CLASSE;
INPUT NOME $ A_CORSO $ - i nomi delle variabili sono separati da blank
A_NASCIT ES_DATI MEDIA; - le prime due variabili sono di tipo carattere
DATALINES; - i dati sono inseriti nel programma;
XXX 1F 1965 12 95 si vedrà in seguito il caso con dati su file
ZZZ 4R 1966 13 100 - ogni linea corrisponde a una osservazione
WWW 4 1968 12 107
TTT 3 1967 9 100
;
PROC SORT data=classe; - lavora sull'ultimo Data Set
BY ES_DATI; run; - ordina le oss. rispetto alla variabile ES_DATI
PROC PRINT data=classe; - stampa le variabili del Data Set con il titolo indicato
TITLE 'STUDENTI ORDINATI PER NUMERO ESAMI DATI';
run; - determina l'esecuzione del passo di proc
PROC CONTENTS data=classe; - stampa le informazioni sul Data Set con il
titolo assegnato precedentemente
PROC MEANS data=classe; - calcola alcune statistiche su tutte le variabili
numeriche con il titolo precedente
RUN; - determina l'esecuzione del passo di proc
PROC MEANS data=classe; - calcola alcune statistiche sulle variabili indicate
var a_nascit; dopo l’istruzioneVAR
RUN; - determina l'esecuzione del passo di proc
8
C2 SECONDO ESEMPIO: LE PROCEDURE PRINT E CONTENTS
PROGRAMMA SAS n. 2:
data es1;
input sesso $ eta hinch wlib;
altezza=hinch*2.54;
peso=wlib*0.4536;
datalines;
f 14 56.3 85.0
f 15 62.3 105.0
f 15 63.3 108.0
f 16 59.0 92.0
f 19 62.5 112.5
f 17 62.5 112.0
f 18 59.0 104.0
f 14 56.5 69.0
f 16 62.0 94.5
f 14 53.8 68.5
f 13 61.5 104.0
f 17 61.5 103.5
f 15 64.5 123.5
f 14 58.3 93.0
f 14 51.3 50.5
f 14 58.8 89.0
f 19 65.3 107.0
f 15 59.5 78.5
f 14 61.3 115.0
f 18 63.3 114.0
f 14 61.8 85.0
(non è riportato una parte dell'INPUT)
m 16 56.8 75.0
m 15 64.8 128.0
m 19 64.5 98.0
m 16 58.0 84.0
m 15 62.8 99.0
m 17 63.8 112.0
m 15 57.8 79.5
m 15 57.3 80.5
m 17 63.5 102.5
m 14 55.0 76.0
m 16 66.5 112.0
m 18 65.0 114.0
m 16 61.5 140.0
m 16 62.0 107.5
;
run;
proc print data=es1;
title ' ';run; i due primi run non sono necessari
proc contents data=es1;run;
9
OUTPUT SAS:
CONTENTS PROCEDURE
10
C3. OSSERVAZIONI PER LA SCRITTURA DEI PROGRAMMI
ESEMPIO 1:
l'istruzione INPUT dell'esempio n.1 può scriversi:
INPUT NOME $ A_CORSO $ VAR1-VAR3;
dopo PROC PRINT si potrebbe mettere l'istruzione:
VAR NOME--VAR3 ;
che sarebbe equivalente a:
VAR NOME A_CORSO VAR1 VAR2 VAR3;
(tale istruzione indica che la PROC deve essere effettuata solo per le variabili indicate)
ESEMPIO 2:
data uno;
input x1 x2 y x3 x5;
datalines;
1 2 3 4 5
6 7 8 9 0
;
proc print; var x1--x3; run; proc print; var x1-x3; run;
1 1 2 3 4 1 1 2 4
2 6 7 8 9 2 6 7 9
proc print; var x1--x5; run; proc print; var x1-x5; run;
1 1 2 3 4 5
2 6 7 8 9 0
D. IL PASSO DI DATA
11
D1. CREAZIONE DI UN DATA SET SAS
OSS: oltre all'istruzione SET si possono usare anche le istruzioni MERGE e PUT con risultato analogo.
12
D2. ALCUNI ESEMPI
PROGRAMMA SAS n. 2:
data es1;
input sesso $ eta hinch wlib;
altezza=hinch*2.54;
peso=wlib*0.4536;
datalines;
f 143 56.3 85.0
f 155 62.3 105.0
f 153 63.3 108.0
f 161 59.0 92.0
f 191 62.5 112.5
f 171 62.5 112.0
f 185 59.0 104.0
f 142 56.5 69.0
f 160 62.0 94.5
f 140 53.8 68.5
f 139 61.5 104.0
f 178 61.5 103.5
m 153 57.8 79.5
m 155 57.3 80.5
m 178 63.5 102.5
m 142 55.0 76.0
m 164 66.5 112.0
m 189 65.0 114.0
m 164 61.5 140.0
m 167 62.0 107.5
;
run;
PROGRAMMA SAS n. 3:
data es2;
infile 'a:es1.txt';
input sesso $ eta hinch wlib;
altezza=hinch*2.54;
peso=wlib*0.4536;
run;
PROGRAMMA SAS n. 4:
data es3;
set es2;
if eta < 16 then cl_eta = 'giovane';
else cl_eta='vecchio';
run;
13
D3. DATA SET SAS PERMANENTI
I Data Set sono conservati con il nome: nome Data Set .SD2 nel path specificato dall'istruzione
LIBNAME.
Esempio.
PROGRAMMA SAS n. 5:
data corso.es3;
set es2;
if eta < 16 then cl_eta = 'giovane';
else cl_eta='vecchio';
run;
I Data Set permanenti sono memorizzati nella directory a:\corsosas. L'istruzione libname
vale per tutti i Data Set costruiti nella sessione.
Il data set costruito è memorizzata nel file a:\corsosas\es3.sd2 che ha la struttura di un Data set
SAS.
data corso.nuovo;
set corso.es3;
14
E. MANIPOLAZIONE DI DATA SET
Consideriamo il seguente esempio.
PROGRAMMA SAS n. 6:
libname corso 'a:\corsosas';
data corso.disney;
input nome $ & sesso $ eta altezza peso;
length nome $ 12;
datalines;
pippo m 32 190 54
paperino m 34 150 50
minnie f 35 145 40
clarabella f 30 180 65
nonna papera f 99 140 55
qui m 8 120 30
quo m 8 120 30
qua m 8 120 30
emy f 8 117 25
ely f 8 117 25
edy f 8 117 25
;
proc print data=corso.disney; run;
OUTPUT SAS:
1 pippo m 32 190 54
2 paperino m 34 150 50
3 minnie f 35 145 40
4 clarabella f 30 180 65
5 nonna papera f 99 140 55
6 qui m 8 120 30
7 quo m 8 120 30
8 qua m 8 120 30
9 emy f 8 117 25
10 ely f 8 117 25
11 edy f 8 117 25
PROGRAMMA SAS n. 7:
l'istruzione: if sesso='m';
può essere sostituita equivalentemente dalle istruzioni if sesso ^='m' then delete;
if sesso ='m' then output;
15
OUTPUT SAS:
1 pippo m 32 190 54
2 paperino m 34 150 50
3 qui m 8 120 30
4 quo m 8 120 30
5 qua m 8 120 30
PROGRAMMA SAS n. 8:
data prime3;
set corso.disney(obs=3);
proc print data=prime3;
data dalla3;
set corso.disney(firstobs=3);
proc print data=dalla3;
data centrali;
set corso.disney(firstobs=3 obs=5);
proc print data=centrali;
run;
OUTPUT SAS:
OBS NOME SESSO ETA ALTEZZA PESO
1 pippo m 32 190 54
2 paperino m 34 150 50
3 minnie f 35 145 40
1 minnie f 35 145 40
2 clarabella f 30 180 65
3 nonna papera f 99 140 55
4 qui m 8 120 30
5 quo m 8 120 30
6 qua m 8 120 30
7 emy f 8 117 25
8 ely f 8 117 25
9 edy f 8 117 25
1 minnie f 35 145 40
2 clarabella f 30 180 65
3 nonna papera f 99 140 55
16
PROGRAMMA SAS n. 8 bis
data es2bis;
infile 'a:es1.txt' firstobs=3;
input sesso $ eta hinch wlib;
proc print data=es2bis;
OUTPUT SAS:
OBS SESSO ETA HINCH WLIB
Esempio:
PROGRAMMA SAS n. 9:
data etasesso;
set corso.disney;
drop altezza peso; oppure keep nome eta sesso;
..............
run;
In tal caso il nuovo Data Set non contiene più le variabili ALTEZZA e PESO, però tali variabili
possono essere usate nelle istruzioni e nel calcolo di nuove variabili (ad es. rapporto=altezza/peso).
DROP e KEEP possono comparire anche come opzioni di un Data Set SAS di input, come segue:
data etasesso;
set corso.disney(drop = altezza peso);
..............
run;
In tal caso le variabili ALTEZZA e PESO non possono essere usate in alcun modo nel nuovo Data Set.
17
E4. CAMBIO DI NOME A VARIABILI
È sufficiente usare l'istruzione RENAME come segue:
data nuovo(rename=(sesso=mf));
set corso.disney;
/* altre istruzioni */
run;
Esempio.
oppure:
1 pippo m 32 190 54
2 paperino m 34 150 50
3 qui m 8 120 30
4 quo m 8 120 30
5 qua m 8 120 30
1 minnie f 35 145 40
2 clarabella f 30 180 65
3 nonna papera f 99 140 55
4 emy f 8 117 25
5 ely f 8 117 25
6 edy f 8 117 25
18
Se la variabile Sesso contenesse un valore diverso da ‘m’ o ‘f’, ad esempio ‘M’, nella finestra di Log si
avrebbe un messaggio come indicato nella istruzione put.
LOG SAS:
osservazioni sbagliate nome=paperino sesso=M eta=34 altezza=150 peso=50 _ERROR_=0 _N_=2
1 pippo m 32 190 54
2 paperino m 34 150 50
3 qui m 8 120 30
4 quo m 8 120 30
5 qua m 8 120 30
6 minnie f 35 145 40
7 clarabella f 30 180 65
8 nonna papera f 99 140 55
9 emy f 8 117 25
10 ely f 8 117 25
11 edy f 8 117 25
1 minnie f 35 145 40
2 clarabella f 30 180 65
3 nonna papera f 99 140 55
4 emy f 8 117 25
5 ely f 8 117 25
19
Il DSS TUTTI2 ha un numero di osservazioni uguale al minimo fra le osservazioni di MASCHI e
FEMMINE; inoltre – in questo caso in cui le variabili dei due DSS sono le stesse – il secondo DSS viene
scritto sul primo.
Le due istruzioni set si possono usare quando i DS hanno variabili diverse (ma rilevate sulla stessa
popolazione), come si vede nel seguente esempio. In questo caso i due DS risultano "affiancati".
OUTPUT SAS:
OBS NOME SESSO ETA ALTEZZA PESO
1 pippo m 32 190 54
2 paperino m 34 150 50
3 qui m 8 120 30
4 quo m 8 120 30
5 qua m 8 120 30
Nella variabile NOME sono scritti i valori assunti nel secondo DS.
Se i Data Set hanno un diverso numero di osservazioni per ciascuna variabile, viene costruito un
nuovo Data Set contenente tutte le variabili dei Data Set precedenti, mettendo a missing le osservazioni
mancanti.
Si potrebbe ottenere un DS simile al precedente utilizzando l'istruzione merge nel seguente modo:
data corso.maschi3s;
merge corso.maschi1s corso.maschi2s;
by nome;
proc print data=corso.maschi1s; run;
OUTPUT SAS:
OBS NOME SESSO ETA ALTEZZA PESO
1 paperino m 34 150 50
2 pippo m 32 190 54
3 qua m 8 120 30
4 qui m 8 120 30
5 quo m 8 120 30
ALTRO ESEMPIO:
20
data uno; data due;
input n $ x y; input n $ x z;
datalines; datalines;
a 12 13 a 22 23
b 14 15 b 24 25
d 16 17 c 26 27
; ;
OUTPUT SAS:
data tre;
set uno; Obs n x y z
set due; 1 a 22 13 23
proc print; run; 2 b 24 15 25
3 c 26 17 27 ATTENZIONE A QUESTA OSSERVAZIONE
OUTPUT SAS:
data quattro; Obs n x y z
merge uno due; 1 a 22 13 23
by n; 2 b 24 15 25
proc print; run; 3 c 26 . 27
4 d 16 17 .
1 0 11 137.818 39
Se si vuole costruire un Data Set con gli scarti dalle medie bisogna operare nel seguente modo.
In tal modo si costruisce un Data Set con le variabili precedenti più le due medie m_alt e m_peso e
le due nuove che sono alt_c e peso_c.
OUTPUT SAS:
21
0BS M_ALT M_PESO NOME SESSO ETA ALTEZZA PESO ALT_C PESO_C
Se non si mettesse l'istruzione if _n_=1 then ... verrebbe costruito un Data Set con tutte
le variabili e un numero di osservazioni pari a quelle di sommario (primo Ds a cui si fa il set).
OUTPUT SAS:
0BS M_ALT M_PESO NOME SESSO ETA ALTEZZA PESO ALT_C PESO_C
22
F. ANCORA SUL PASSO DI DATA
F1. ESPRESSIONI E FUNZIONI SAS
ESPRESSIONI SAS
Sono le solite: costanti, date, operatori sia su variabili carattere che numeriche, ecc.
FUNZIONI SAS
Le funzioni del SAS, così come in tutti gli altri linguaggi di programmazione, sono dei programmi
già scritti che si richiamano con una parola chiave e ritornano un valore calcolato sugli argomenti che
vengono passati alla funzione.
Il formato delle funzioni può essere uno dei seguenti:
NOME-FUNZIONE (arg1 , arg2 , ... , argn );
NOME-FUNZIONE (OF var1 - varn );
NOME-FUNZIONE (OF var1 var2 var3......varn );
(il più comune è il primo tipo presentato)
23
DIFFERENZA TRA FUNZIONI E PROCEDURE
Le funzioni producono statistiche per ogni osservazione (riga) nel Data Set SAS e producono
risultati pari al numero di osservazioni.
Le procedure producono statistiche per le variabili (colonne) nel Data Set SAS.
data temperature;
input citta $ t6 t12 t18;
media_temp=mean(t6,t12,t18); istruzioni equivalenti media_temp=mean(of t6 t12 t18);
media_temp=mean(of t6—-t18);
datalines;
Genova 19 24 22
Milano 15 18 18
Napoli 26 30 29
;
run;
OUTPUT SAS
proc print;
run; Obs citta t8 t12 t18 media_temp
1 Genova 19 24 22 21.6667
2 Milano 15 18 18 17.0000
3 Napoli 26 30 29 28.3333
I valori mancanti si propagano nelle espressioni aritmetiche; nelle funzioni, invece, il discorso
cambia. I valori mancanti nei confronti vengono messi a "meno infinito".
Esempio.
data es5;
input dato1 dato2;
somma=dato1+dato2;
totale=sum(dato1,dato2);
media1=(dato1+dato2)/2;
media2=mean(dato1,dato2);
datalines;
1 3
6 4
. 78
8 1
12 14
;
proc print;run;
24
OUTPUT SAS:
Obs dato1 dato2 somma totale media1 media2
1 1 3 4 4 2.0 2.0
2 6 4 10 10 5.0 5.0
3 . 78 . 78 . 78.0
4 8 1 9 9 4.5 4.5
5 12 14 26 26 13.0 13.0
Osservare che:
. + 78 ha come risultato .
sum( . , 78) ha come risultato 78
In generale le funzioni "ignorano" i valori missing; con SUM i missing sono considerati 0, con MEAN
viene fatta la somma dei valori non missing e il risultato viene diviso per il numero dei valori non
missing, ... .
Istruzione RETAIN
E' una istruzione non eseguibile e quindi può essere messa in qualunque punto del passo di DATA;
svolge le due seguenti funzioni:
- trattiene i valori delle variabili dalla precedente esecuzione del passo di Data
- assegna dei valori iniziali alle variabili.
La sintassi dell'istruzione RETAIN è la seguente:
25
Istruzione somma
Per effettuare somme cumulate, come nell’esempio precedente per la variabile CONTO, si può usare la
seguente espressione sintetica:
CONTO + 3;
Che corrisponde alle istruzioni
Retain CONTO 0;
CONTO=sum(CONTO, 3);
La sua sintassi generale è:
variabile + espressione;
DATA ADD;
RETAIN CONTO TOTALE 0; OUTPUT SAS:
INPUT PUNTEGGI;
TOTALE=TOTALE+PUNTEGGI; OBS CONTO TOTALE PUNTEGGI
CONTO=CONTO+3; 1 3 10 10
DATALINES; 2 6 13 3
10 3 9 20 7
3 4 12 . .
7 5 15 . 6
. (missing value) 6 18 . 4
6
4
;
PROC PRINT;RUN;
Se si volesse avere TOTALE con valore anche per le osservazioni 4, 5 e 6 si dovrebbe fare:
TOTALE = SUM (TOTALE, PUNTEGGI);
26
F4. APPROFONDIMENTI SUL PASSO DI DATA (tratto da Help on line SAS)
Flow of Action
When you submit a DATA step for execution, it is first compiled and then executed. The following figure
shows the flow of action for a typical SAS DATA step.
Flow of Action in the DATA Step
27
The Compilation Phase
When you submit a DATA step for execution, SAS checks the syntax of the SAS statements and
compiles them, that is, automatically translates the statements into machine code. In this phase, SAS
identifies the type and length of each new variable, and determines whether a type conversion is
necessary for each subsequent reference to a variable. During the compile phase, SAS creates the
following three items:
input buffer is a logical area in memory into which SAS reads each record of raw data when SAS
executes an INPUT statement. Note that this buffer is created only when the DATA step
reads raw data. (When the DATA step reads a SAS data set, SAS reads the data directly
into the program data vector.)
program data is a logical area in memory where SAS builds a data set, one observation at a time.
vector (PDV) When a program executes, SAS reads data values from the input buffer or creates them
by executing SAS language statements. The data values are assigned to the appropriate
variables in the program data vector. From here, SAS writes the values to a SAS data set
as a single observation.
Along with data set variables and computed variables, the PDV contains two automatic
variables, _N_ and _ERROR_. The _N_ variable counts the number of times the DATA
step begins to iterate. The _ERROR_ variable signals the occurrence of an error caused
by the data during execution. The value of _ERROR_ is either 0 (indicating no errors
exist), or 1 (indicating that one or more errors have occurred). SAS does not write these
variables to the output data set.
descriptor is information that SAS creates and maintains about each SAS data set, including data
information set attributes and variable attributes. It contains, for example, the name of the data set
and its member type, the date and time that the data set was created, and the number,
names and data types (character or numeric) of the variables.
The Execution Phase
By default, a simple DATA step iterates once for each observation that is being created. The flow of
action in the Execution Phase of a simple DATA step is described as follows:
1. The DATA step begins with a DATA statement. Each time the DATA statement executes, a new
iteration of the DATA step begins, and the _N_ automatic variable is incremented by 1.
2. SAS sets the newly created program variables to missing in the program data vector (PDV).
3. SAS reads a data record from a raw data file into the input buffer, or it reads an observation from
a SAS data set directly into the program data vector. You can use an INPUT, MERGE, SET,
MODIFY, or UPDATE statement to read a record.
4. SAS executes any subsequent programming statements for the current record.
5. At the end of the statements, an output, return, and reset occur automatically. SAS writes an
observation to the SAS data set, the system automatically returns to the top of the DATA step, and
the values of variables created by INPUT and assignment statements are reset to missing in the
program data vector. Note that variables that you read with a SET, MERGE, MODIFY, or
UPDATE statement are not reset to missing here.
6. SAS counts another iteration, reads the next record or observation, and executes the subsequent
programming statements for the current observation.
7. The DATA step terminates when SAS encounters the end-of-file in a SAS data set or a raw data file.
Note: The figure shows the default processing of the DATA step. You can code data-reading statements
(such as INPUT or SET), or data-writing statements (such as OUTPUT), in any order in your program.
28
Processing a DATA Step: A Walkthrough
Sample DATA Step
The following statements provide an example of a DATA step that reads raw data, calculates totals, and
creates a data set:
data total_points (drop=TeamName); [1]
input TeamName $ ParticipantName $ Event1 Event2 Event3; [2]
TeamTotal + (Event1 + Event2 + Event3); [3]
datalines;
Knights Sue 6 8 8
Cardinals Jane 9 7 8
Knights John 7 7 7
Knights Lisa 8 9 9
Knights Fran 7 6 6
Knights Walter 9 8 10
;
The DROP= data set option prevents the variable TeamName from being written to the output SAS
data set called TOTAL_POINTS.
The INPUT statement describes the data by giving a name to each variable, identifying its data type
(character or numeric), and identifying its relative location in the data record.
The Sum statement accumulates the scores for three events in the variable TeamTotal.
Variables that are created by the INPUT and the Sum statements (TeamName, ParticipantName, Event1,
Event2, Event3, and TeamTotal) are set to missing initially. Note that in this representation, numeric
variables are initialized with a period and character variables are initialized with blanks. The automatic
variable _N_ is set to 1; the automatic variable _ERROR_ is set to 0.
The variable TeamName is marked Drop in the PDV because of the DROP= data set option in the DATA
statement. Dropped variables are not written to the SAS data set. The _N_ and _ERROR_ variables are
dropped because automatic variables created by the DATA step are not written to a SAS data set. See
SAS Variables for details about automatic variables.
29
Reading a Record
SAS reads the first data line into the input buffer. The input pointer, which SAS uses to keep its place as
it reads data from the input buffer, is positioned at the beginning of the buffer, ready to read the data
record. The following figure shows the position of the input pointer in the input buffer before SAS reads
the data.
Position of the Pointer in the Input Buffer Before SAS Reads Data
The INPUT statement then reads data values from the record in the input buffer and writes them to the
PDV where they become variable values. The following figure shows both the position of the pointer in
the input buffer, and the values in the PDV after SAS reads the first record.
Values from the First Record are Read into the Program Data Vector
After the INPUT statement reads a value for each variable, SAS executes the Sum statement. SAS
computes a value for the variable TeamTotal and writes it to the PDV. The following figure shows the
PDV with all of its values before SAS writes the observation to the data set.
Program Data Vector with Computed Value of the Sum Statement
SAS then returns to the DATA statement to begin the next iteration. SAS resets the values in the PDV in
the following way:
! The values of variables created by the INPUT statement are set to missing.
! The value created by the Sum statement is automatically retained.
! The value of the automatic variable _N_ is incremented by 1, and the value of _ERROR_ is reset
to 0.
The following figure shows the current values in the PDV.
30
Current Values in the Program Data Vector
As SAS continues to read records, the value in TeamTotal grows larger as more participant scores are
added to the variable. _N_ is incremented at the beginning of each iteration of the DATA step. This
process continues until SAS reaches the end of the input file.
Participant Team
Obs Name Event1 Event2 Event3 Total
1 Sue 6 8 8 22
2 Jane 9 7 8 46
3 John 7 7 7 67
4 Lisa 8 9 9 93
5 Fran 7 6 6 112
6 Walter 9 8 10 139
31
F5. GLI ARRAY (tratto da Help on line SAS)
Syntax
ARRAY array-name { subscript } <$><length> <array-elements> <(initial-value-list)>; !
"#$%&'()*!!
array-name
names the array.
{subscript}
describes the number and arrangement of elements in the array by using an asterisk, a number, or
a range of numbers. Subscript has one of these forms:
{dimension-size(s)}
indicates the number of elements in each dimension of the array. Dimension-size is a numeric
representation of either the number of elements in a one-dimensional array or the number of
elements in each dimension of a multidimensional array.
$
indicates that the elements in the array are character element.
length
specifies the length of elements in the array that have not been previously assigned a length.
array-elements
names the elements that make up the array. Array-elements must be either all numeric or all
character, and they can be listed in any order. The elements can be
variables
lists variable names. (initial-value-list)
gives initial values for the corresponding elements in the array. The values for elements can be
numbers or character strings. You must enclose all character strings in quotation marks. To
specify one or more initial values directly, use the following format:
(initial-value(s))
To specify an iteration factor and nested sublists for the initial values, use the following format:
<constant-iter-value*> <(>constant value | constant-sublist<)>
Examples!
+,-&./'!01!2'34(4($!"##-5*!!
! array rain {5} janr febr marr aprr mayr;
! array days{7} d1-d7;
! array month{*} jan feb jul oct nov;
! array x{*} _NUMERIC_;
! array qbx{10};
! array meal{3};
+,-&./'!61!"**4$(4($!7(4)4-/!8%&'#49!:-/%'*!!
! array test{4} t1 t2 t3 t4 (90 80 70 70);
! array test{4} t1-t4 (90 80 2*70);
! array test{4} _TEMPORARY_ (90 80 70 70);
+,-&./'!;1!2'34(4($!7(4)4-/!<=-#-9)'#!:-/%'*!!
! array test2{*} a1 a2 a3 ('a','b','c');
32
+,-&./'!>1!?*4($!7)'#-)4@'!2ABCDD.!E#D9'**4($!!
In this example, the statements process each element of the array, using the value of variable I as the
subscript on the array references for each iteration of the DO loop. If an array element has a value of 99,
the IF-THEN statement changes that value to 100.
array days{7} d1-d7;
do i=1 to 7;
if days{i}=99 then days{i}=100;
end;
+,-&./'!F1!G'3'#'(94($!H-(5!"##-5*!4(!A('!I)-)'&'()!!
You can refer to more than one array in a single SAS statement. In this example, you create two arrays,
DAYS and HOURS. The statements inside the DO loop substitute the current value of variable I to
reference each array element in both arrays.
array days{7} d1-d7;
array hours{7} h1-h7;
do i=1 to 7;
if days{i}=99 then days{i}=100;
hours{i}=days{i}*24;
end;
+,-&./'!J1!?*4($!)='!"*)'#4*K!G'3'#'(9'*!-*!-!:-#4-L/'!C4*)!!
! array cost{10} cost1-cost10;
totcost=sum(of cost {*});
! array days{7} d1-d7;
input days {*};
! array hours{7} h1-h7;
put hours {*};
- l'istruzione IF espressione ;
è equivalente all'espressione IF (¬ espressione ) THEN DELETE;
33
ESEMPIO. PROGRAMMA SAS n 21:
data corso.maschi corso.femmine;
set corso.disney;
if sesso='m' then output corso.maschi;
else if sesso='f' then output corso.femmine;
else put 'osservazioni sbagliate ' _all_;
run;
Attenzione: SELECT si può usare solo per valori esatti, altrimenti usare IF
attenzione: nel Data Set viene scritto solo il valore che le variabili (create o modificate nelle
istruzioni che compaiono "dentro il DO") hanno alla fine dell'esecuzione dell'istruzione
DO; se si vuole conservare il valore delle variabili a ogni passo del DO è necessario
scrivere "dentro il DO" l'istruzione OUTPUT;
34
ESEMPIO. PROGRAMMA SAS n. 22:
data es4;
do i=-1 to 1 by .1;
x=probnorm(i);
output;
end;
proc print; run;
OUTPUT SAS:
OBS I X
1 -1.00000 0.15866
2 -0.90000 0.18406
3 -0.80000 0.21186
4 -0.70000 0.24196
5 -0.60000 0.27425
6 -0.50000 0.30854
7 -0.40000 0.34458
8 -0.30000 0.38209
9 -0.20000 0.42074
10 -0.10000 0.46017
11 -0.00000 0.50000
12 0.10000 0.53983
13 0.20000 0.57926
14 0.30000 0.61791
15 0.40000 0.65542
16 0.50000 0.69146
17 0.60000 0.72575
18 0.70000 0.75804
19 0.80000 0.78814
20 0.90000 0.81594
21 1.00000 0.84134
4) DO WHILE (espressione )
5) DO UNTIL (espressione )
per le istruzioni DO WHILE e DO UNTIL valgono le stesse considerazioni fatte per l'istruzione DO a
proposito dell'istruzione OUTPUT
7) LINK etichetta ;
35
ESEMPI DI USO DEL CICLO DO
data uno;
input x y a$;
COSTRUZIONE DATA SET ORIGINALE datalines;
5 7 n
3 2 a
4 7 a
2 1 n
5 5 n
;
36
data sei; Obs x y a i z
set uno;
do i=y, x; 1 5 7 n 7 35
z=x*i; 2 5 7 n 5 25
output; 3 3 2 a 2 6
end; 4 3 2 a 3 9
proc print;run; 5 4 7 a 7 28
6 4 7 a 4 16
7 2 1 n 1 2
8 2 1 n 2 4
9 5 5 n 5 25
10 5 5 n 5 25
37
data dieci; Obs x y a i z
set uno;
do i='r','s','t'; 1 5 7 n r nr
z=trim(a)||i; 2 5 7 n s ns
output; 3 5 7 n t nt
end; 4 3 2 a r ar
proc print;run; 5 3 2 a s as
6 3 2 a t at
7 4 7 a r ar
8 4 7 a s as
9 4 7 a t at
10 2 1 n r nr
11 2 1 n s ns
12 2 1 n t nt
13 5 5 n r nr
14 5 5 n s ns
15 5 5 n t nt
38
F7. L' ISTRUZIONE INPUT
L'istruzione INPUT si leggono dati grezzi (non Data Set SAS) su file, residenti su disco, ecc.
Non ci sono limiti al numero di istruzioni INPUT che possono comparire in un passo di Data.
Ciascuna istruzione INPUT legge:
- da un file indirizzato da una istruzione INFILE che deve precedere la istruzione INPUT
- da programma se non compare alcuna istruzione INFILE. In tal caso per segnalare al SAS l'inizio dei
dati, deve comparire una istruzione DATALINES (o CARDS) come ultima istruzione del passo di Data
ed immediatamente prima dell'inizio dei dati.
In SAS sono possibili vari tipi di input, di cui i principali sono:
1) a colonne
2) a lista
3) a formato
E' possibile nella stessa istruzione combinare i tre tipi di input.
INPUT A COLONNE:
- le variabili carattere possono essere al massimo lunghe 200 caratteri (da precisare con l'istruzione
LENGHT) e possono avere spazi come caratteri propri del campo (ad es. DE LUCA).
- i valori carattere, prima di essere assegnati alle variabili, sono allineati a sinistra.
Ad esempio, avendo l'istruzione INPUT SESSO $ 1-3 allora:
M (il valore della variabile compare in prima colonna)
M (il valore della variabile compare in seconda colonna)
M (il valore della variabile compare in terza colonna)
sono letti allo stesso modo.
- i valori numerici possono comparire ovunque nel campo; possono essere specificati il segno, le cifre
decimali o l'esponente.
Esempio:
con l'istruzione INPUT X 1-6;
si può leggere uno dei seguenti numeri 23
(il segno € indica uno spazio bianco) 23.0
2.3E1
23
-23
- in un campo numerico non sono permessi spazi bianchi (esempio: - 23 )
39
INPUT A LISTA:
ESEMPI
FILE DI INPUT:
Country Car MPG Weight Drive Horse Displa Cyl. Accel.
Ratio power cement
U.S. Buick Estate Wagon 16.9 4.360 2.73 155 350 8 14.9
U.S. Ford Country Squire Wagon 15.5 4.054 2.26 142 351 8 14.3
U.S. Chevy Malibu Wagon 19.2 3.605 2.56 125 267 8 15.0
U.S. Chrysler LeBaron Wagon 18.5 3.940 2.45 150 360 8 13.0
U.S. Chevette 30.0 2.155 3.70 68 98 4 16.5
Japan Toyota Corona 27.5 2.560 3.05 95 134 4 14.2
Japan Datsun 510 27.2 2.300 3.54 97 119 4 14.7
U.S. Dodge Omni 30.9 2.230 3.37 75 105 4 14.5
Germany Audi 5000 20.3 2.830 3.90 103 131 5 15.9
Sweden Volvo 240 GL 17.0 3.140 3.50 125 163 6 13.6
Sweden Saab 99 GLE 21.6 2.795 3.77 115 121 4 15.7
France Peugeot 694 SL 16.2 3.410 3.58 133 163 6 15.8
U.S. Buick Century Special 20.6 3.380 2.73 105 231 6 15.8
U.S. Mercury Zephyr 20.8 3.070 3.08 85 200 6 16.7
U.S. Dodge Aspen 18.6 3.620 2.71 110 225 6 18.7
U.S. AMC Concord D/L 18.1 3.410 2.73 120 258 6 15.1
U.S. Chevy Caprice Classic 17.0 3.840 2.41 130 305 8 15.4
U.S. Ford LTD 17.6 3.725 2.26 129 302 8 13.4
U.S. Mercury Grand Marquis 16.5 3.955 2.26 138 351 8 13.2
U.S. Dodge St Regis 18.2 3.830 2.45 135 318 8 15.2
U.S. Ford Mustang 4 26.5 2.585 3.08 88 140 4 14.4
U.S. Ford Mustang Ghia 21.9 2.910 3.08 109 171 6 16.6
Japan Mazda GLC 34.1 1.975 3.73 65 86 4 15.2
Japan Dodge Colt 35.1 1.915 2.97 80 98 4 14.4
U.S. AMC Spirit 27.4 2.670 3.08 80 121 4 15.0
Germany VW Scirocco 31.5 1.990 3.78 71 89 4 14.9
Japan Honda Accord LX 29.5 2.135 3.05 68 98 4 16.6
U.S. Buick Skylark 28.4 2.670 2.53 90 151 4 16.0
U.S. Chevy Citation 28.8 2.595 2.69 115 173 6 11.3
U.S. Olds Omega 26.8 2.700 2.84 115 173 6 12.9
U.S. Pontiac Phoenix 33.5 2.556 2.69 90 151 4 13.2
U.S. Plymouth Horizon 34.2 2.200 3.37 70 105 4 13.2
Japan Datsun 210 31.8 2.020 3.70 65 85 4 19.2
Italy Fiat Strada 37.3 2.130 3.10 69 91 4 14.7
Germany VW Dasher 30.5 2.190 3.70 78 97 4 14.1
Japan Datsun 810 22.0 2.815 3.70 97 146 6 14.5
Germany BMW 320i 21.5 2.600 3.64 110 121 4 12.8
Germany VW Rabbit 31.9 1.925 3.78 71 89 4 14.0
40
PROGRAMMA SAS n. 23:
data corso.CARS;
infile 'a:\acp.txt' firstobs=3;
length TIPO $ 25;
input NAZIONE $ TIPO $ & CONSUMO PESO DRIVE_R POTENZA
CILINDRA NUM_C RIPRESA;
OBS TIPO NAZIONE CONSUMO PESO DR_R POTEN CILIN NUM_C RIPRESA
1 Buick Estate Wagon U.S. 16.9 4.36 2.73 155 350 8 14.9
2 Ford Country Squire Wagon U.S. 15.5 4.05 2.26 142 351 8 14.3
3 Chevy Malibu Wagon U.S. 19.2 3.61 2.56 125 267 8 15.0
4 Chrysler LeBaron Wagon U.S. 18.5 3.94 2.45 150 360 8 13.0
5 Chevette U.S. 30.0 2.16 3.70 68 98 4 16.5
6 Toyota Corona Japan 27.5 2.56 3.05 95 134 4 14.2
7 Datsun 510 Japan 27.2 2.30 3.54 97 119 4 14.7
8 Dodge Omni U.S. 30.9 2.23 3.37 75 105 4 14.5
9 Audi 5000 Germany 20.3 2.83 3.90 103 131 5 15.9
10 Volvo 240 GL Sweden 17.0 3.14 3.50 125 163 6 13.6
11 Saab 99 GLE Sweden 21.6 2.80 3.77 115 121 4 15.7
12 Peugeot 694 SL France 16.2 3.41 3.58 133 163 6 15.8
13 Buick Century Special U.S. 20.6 3.38 2.73 105 231 6 15.8
14 Mercury Zephyr U.S. 20.8 3.07 3.08 85 200 6 16.7
15 Dodge Aspen U.S. 18.6 3.62 2.71 110 225 6 18.7
16 AMC Concord D/L U.S. 18.1 3.41 2.73 120 258 6 15.1
17 Chevy Caprice Classic U.S. 17.0 3.84 2.41 130 305 8 15.4
18 Ford LTD U.S. 17.6 3.73 2.26 129 302 8 13.4
19 Mercury Grand Marquis U.S. 16.5 3.96 2.26 138 351 8 13.2
20 Dodge St Regis U.S. 18.2 3.83 2.45 135 318 8 15.2
41
INPUT A FORMATO:
dove:
- puntatore può essere uno dei seguenti:
+n il cursore si sposta di n colonne
/ il cursore va alla prima colonna del record successivo
# n il cursore si posiziona alla prima colonna del record n
@ n il cursore si posiziona alla colonna n
@ 'carattere ' il cursore si posiziona alla prima colonna diversa da blank dopo il carattere indicato
@@ indica che i dati di un record si riferiscono a più osservazioni
- formato può essere uno dei seguenti (sono elencati i più comuni):
w. formato per leggere un campo numerico lungo w cifre;
w.d formato per leggere un campo numerico lungo w cifre di cui d decimali;
$w. formato per leggere un campo alfanumerico lungo w caratteri;
$CHARw. formato per leggere un campo alfanumerico lungo w caratteri contenente blank;
Ew. formato esadecimale.
Con l'input a formato i valori mancanti vanno codificati con un punto o con degli spazi.
Si possono considerare variabili numeriche con 0 al posto di blank.
Si possono leggere anche "date" (in notazione inglese, italiana,...).
Esempio
data es1;
input sesso $ eta :3.1 hinch wlib @@;
altezza=hinch*2.54;
peso=wlib*0.4536;
datalines;
f 143 56.3 85.0 f 155 62.3 105.0 f 153 63.3 108.0 f 161 59.0 92.0
f 191 62.5 112.5 f 171 62.5 112.0 f 185 59.0 104.0 f 142 56.5 69.0
f 160 62.0 94.5 f 140 53.8 68.5 f 139 61.5 104.0 f 178 61.5 103.5
f 157 64.5 123.5 f 149 58.3 93.0 f 143 51.3 50.5 f 145 58.8 89.0
f 191 65.3 107.0 f 150 59.5 78.5 f 147 61.3 115.0 f 180 63.3 114.0
f 141 61.8 85.0 f 140 53.5 81.0 f 164 58.0 83.5 f 176 61.3 112.0
;
run;
Esempio:
E' possibile raggruppare i dati che vanno letti con il medesimo formato e raggruppare il formato
come nel seguente esempio:
INPUT GEN 3. FEB 3. MAR 3.;
può essere indifferentemente scritto come:
INPUT (GEN FEB MAR) (3. 3. 3.);
INPUT (GEN FEB MAR) (3.);
42
COMBINAZIONE DEI DIVERSI TIPI DI INPUT:
la variabile NOME è letta a lista, la variabile SESSO a formato, la variabile ETA a colonna, la variabile
ALTEZZA a lista, la variabile PESO a formato.
Ogni volta che viene eseguita un'istruzione INPUT viene letto un record; se i dati relativi a una
osservazione si trovano su più record bisogna mettere più istruzioni INPUT.
Esempio:
DATA CLASSE;
INPUT NOME $ 1-8 SESSO $ 11;
INPUT ETA 3-4;
INPUT ALTEZZA 1-4 PESO 6-10;
DATALINES;
GIANNI M
12
155 48.2
MARCO M
12
151 43.7
/* altri dati */
;
RUN;
Questa istruzione identifica un file in formato testo da cui si vogliono leggere i dati tramite
l'istruzione input. La sintassi è:
infile nomefile opzioni;
La principali opzioni sono:
firstobs = n. primo record da leggere
obs = n. ultimo record da leggere
Esempio:
data pippo;
infile 'a:pluto.txt' firstobs=3 obs=10;
input x1-x5;
run;
Vengono letti i record dal terzo al decimo.
43
F9. L'ISTRUZIONE OUTPUT
Quando una istruzione di OUTPUT è presente in un passo di Data, il SAS aggiunge osservazioni al
Data Set solo quando viene eseguita l'istruzione OUTPUT. In sostanza questa istruzione inibisce la
scrittura implicita operata dal SAS al termine del passo di Data.
data corso.maschi;
set corso.disney;
if sesso='m' then output;
run;
L'istruzione PUT è l'equivalente dell'istruzione INPUT per la scrittura e specifica cosa e come
scrivere ciascuna linea. La forma generale dell'istruzione è:
PUT [specifiche ];
dove le specifiche indicano lo stile da usare; esso può essere:
- a lista - a colonna - a formato - a stringa - guidato
(a noi interessano solo i primi tre casi)
Analogamente all'istruzione INPUT, i vari modi di scrittura possono venire usati in una stessa
istruzione PUT.
Se non viene definito un file esterno, l'istruzione PUT stampa i dati nella finestra di Log.
In uno stesso passo di Data possono essere creati più files su dischi contenenti i risultati dell'analisi
effettuata. Ciascuno di questi Data Set deve essere "puntato" da una istruzione FILE, la cui sintassi nella
forma generale è quella scritta sopra.
44
G. PASSO DI PROC
TITLE e FOOTNOTE rimangono attivi anche in successivi passi di PROC fino a quando non vengono
ridefiniti o annullati.
VAR variabili;
indica su quali variabili deve operare la procedura.
WHERE espressione;
permette di selezionare osservazioni dal Data Set su cui opera la procedura.
Esempio
OUTPUT SAS
PROGRAMMA SAS N. 25 bis:
Obs NAZIONE TIPO PESO
proc print data=a.cars;
var nazione tipo peso; 9 Germany Audi 5000 1.28369
where nazione='Germany'; 26 Germany VW Scirocco 0.90266
run; 35 Germany VW Dasher 0.99338
37 Germany BMW 320i 1.17936
Osservare che nella colonna Obs rimane il numero 38 Germany VW Rabbit 0.87318
dell’osservazione del DSS
45
G2. LA PROCEDURA SORT
Questa procedura esegue l'ordinamento di valori numerici o carattere (secondo il codice ASCII).
La sintassi è la seguente:
PROC SORT [opzioni] ;
BY [DESCENDING] variabile [DESCENDING] variabile ...;
L'istruzione BY deve sempre essere specificata. L'opzione DESCENDING indica che la variabile
deve essere ordinata in ordine decrescente. Quando ci sono più variabili specificate con BY
l'ordinamento viene fatto a partire dalla prima.
Esempio:
1 emy f 8 117 25
2 ely f 8 117 25
3 edy f 8 117 25
4 clarabella f 30 180 65
5 minnie f 35 145 40
6 nonna papera f 99 140 55
7 qui m 8 120 30
8 quo m 8 120 30
9 qua m 8 120 30
10 pippo m 32 190 54
11 paperino m 34 150 50
46
G3. LA PROCEDURA PRINT
- NOOBS
elimina dall'output la colonna con il numero progressivo delle osservazioni
- ROUND
arrotonda i dati alla seconda cifra decimale
- BY lista variabili ;
per avere una stampa separata su osservazioni raggruppate secondo le variabili definite da BY
(attenzione i dati devono essere già ordinati).
47
Esempio:
data corso.dis_eta;
set corso.disney;
e='giovane';
if eta>10 then e='vecchio';
proc sort data=corso.dis_eta out=eta1;
by e sesso;
proc print;
by e sesso;
run;
OUTPUT SAS:
1 emy 8 117 25
2 ely 8 117 25
3 edy 8 117 25
4 qui 8 120 30
5 quo 8 120 30
6 qua 8 120 30
7 minnie 35 145 40
8 clarabella 30 180 65
9 nonna papera 99 140 55
10 pippo 32 190 54
11 paperino 34 150 50
48
- SUM lista variabili ;
indica che devono essere stampati i totali delle variabili elencate.
- SUMBY variabile ;
va usata solo nel caso sia presente una istruzione BY ed una SUM con più variabili; la variabile
specificata deve comparire nella istruzione BY. Ogni volta che tale variabile cambia valore, vengono
stampati i totali delle variabili che sono specificate nella istruzione SUM.
Esempio:
OUTPUT SAS:
1 minnie 35 145 40
2 clarabella 30 180 65
3 nonna papera 99 140 55
4 emy 8 117 25
5 ely 8 117 25
6 edy 8 117 25
--- ------- ----
SESSO 188 816 235
7 pippo 32 190 54
8 paperino 34 150 50
9 qui 8 120 30
10 quo 8 120 30
11 qua 8 120 30
--- ------- ----
SESSO 90 700 194
=== ======= ====
278 1516 429
49
G4. LA PROCEDURA MEANS
La procedura serve per produrre statistiche relative a tutte le osservazioni di un Data Set SAS.
La sintassi è la seguente:
PROC MEANS [opzioni ] ;
Alcune opzioni sono:
- DATA = nome Data Set SAS
specifica il Data Set su cui vengono calcolate le statistiche. Se omesso, si considera l'ultimo creato.
- NOPRINT
sopprime la stampa dei risultati nella finestra di output
- MAXDEC = n
indica il numero di cifre decimali desiderate.
- VARDEF = DF | N | ...
specifica il denominatore della formula della varianza. Il default è DF=(numero dati - 1).
Esempio:
PROGRAMMA SAS n. 29:
OUTPUT SAS:
1 0 11 137.818 39
50
Può essere richiesto il calcolo delle seguenti statistiche (che vanno specificate come opzioni se si
vogliono diverse da quelle di default che sono indicate nella prima colonna):
OUTPUT SAS:
------------------------------------- SESSO=f ---------------------------------
1 f 0 6 136 39.1667
2 m 0 5 140 38.8000
51
G5. LA PROCEDURA FREQ
Conteggia le frequenze dei valori e produce tavole mono- o n-dimensionali con frequenze,
frequenze cumulate, percentuali, percentuali cumulate.
La sintassi è la seguete:
PROC FREQ [opzioni ];
- BY variabili ;
può essere usato per ottenere analisi separate per i gruppi definiti.
Opzioni di TABLES:
52
PROGRAMMA SAS n. 32:
OUTPUT SAS:
Cumulative Cumulative
ALTEZZA Frequency Percent Frequency Percent
-----------------------------------------------------
128.27 1 0.4 1 0.4
130.302 1 0.4 2 0.8
130.81 1 0.4 3 1.2
133.35 1 0.4 4 1.6
134.112 1 0.4 5 2.0
135.382 1 0.4 6 2.3
135.89 1 0.4 7 2.7
136.652 1 0.4 8 3.1
138.43 2 0.8 10 3.9
1 128.270 1 0.39063
2 130.302 1 0.39063
3 130.810 1 0.39063
4 133.350 1 0.39063
Per conservare anche le frequenze cumulate (assolute o relative) si procede nel seguente modo:
data freq_al2;
set freq_alt;
fc_ass+count;
fc_perc+percent;
proc print; run;
53
OUTPUT SAS:
OBS ALTEZZA COUNT PERCENT FC_ASS FC_PERC
La PROC FREQ è soprattutto utilizzata per costruire tabelle di contingenza a due o più vie
(attenzione: questo ha senso per variabili qualitative o variabili quantitative che assumono un numero
"piccolo" di valori).
OUTPUT SAS:
TABLE OF E BY SESSO
E SESSO
Frequency|
Percent |
Row Pct |
Col Pct |f |m | Total
---------+--------+--------+
giovane | 3 | 3 | 6
| 27.27 | 27.27 | 54.55
| 50.00 | 50.00 |
| 50.00 | 60.00 |
---------+--------+--------+
vecchio | 3 | 2 | 5
| 27.27 | 18.18 | 45.45
| 60.00 | 40.00 |
| 50.00 | 40.00 |
---------+--------+--------+
Total 6 5 11
54.55 45.45 100.00
54
DIVISIONE IN CLASSI DI UNA VARIABILE QUANTITATIVA ATTRAVERSO LA
PROCEDURA FORMAT
Attenzione: dal punto di vista statistico la suddivisione in classi di una variabile quantitativa è
spesso un'operazione ARBITRARIA che può falsare i risultati.
value c_peso
low -< 40 = 'magri'
40 -< 60 = 'medi'
60 -< high = 'grassi';
PROCEDURA FREQ:
OUTPUT SAS:
TABLE OF ETA BY PESO
ETA PESO
Percent |magri |medi |grassi | Total
--------+--------+--------+--------+
giovani | 24.22 | 22.66 | 0.39 | 47.27
--------+--------+--------+--------+
medi | 5.47 | 24.22 | 1.56 | 31.25
--------+--------+--------+--------+
vecchi | 0.39 | 14.84 | 6.25 | 21.48
--------+--------+--------+--------+
Total 77 158 21 256
30.08 61.72 8.20 100.00
ETA ALTEZZA
55
G6. LA PROCEDURA UNIVARIATE
La procedura produce statistiche descrittive per le variabili numeriche, quali valori estremi della
variabile, quantili, tabelle di frequenza, grafica box plot e stem and leaf.
La sintassi è la seguente:
PROC UNIVARIATE [opzioni ];
Alcune opzioni sono:
- DATA = nome Data Set SAS
- NOPRINT
sopprime tutte le stampe dell'output. Può essere usato quando si vuole creare un nuovo Data Set.
- PLOT
produce uno stem-and-leaf plot, un box plot e un grafico della funzione di ripartizione empirica
sovrapposto a quello della funzione di ripartizione della Normale
- FREQ
crea una tabella di frequenza con i valori della variabile, le relative frequenze, percentuali, e
percentuali cumulate
- NORMAL
effettua un test per verificare se i dati provengono da una distribuzione Normale
- PCTLDEF = valore
specifica con quale formula calcolare il quantile.
- VARDEF = DF | WEIGHT | N | WDF
specifica il divisore da usare nel calcolo della varianza
(DF indica che devono essere usati i gradi di libertà , N-1; WEIGHT indica che deve essere usata la
somma dei pesi; N indica che si usa il numero delle osservazioni; WDF indica che si usa la somma dei
pesi meno 1). Il default è DF.
specifica le unità da usare per arrotondare i valori delle variabili
- per il calcolo di percentili addizionali a quelli di default elencati sotto:
- PCTLNAME = nomi dei percentili specifica i nomi dei percentili
- PCTLPTS = valori dei percentili specifica quali percentili sono da calcolare
- PCTLPRE = prefissi delle variabili specifica i prefissi da usare nel DS di output
per le variabili contenenti i nuovi percentili
56
Le parole chiavi ammesse sono:
N NMISS NOBS MEAN SUM STD VAR SKEWNESS KURTOSIS SUMWGT
MAX MIN RANGE Q3 MEDIAN Q1 QRANGE P1 P5 P10 P90 P95
P99 MODE SIGNRANK NORMAL
(con i significati già indicati)
OUTPUT SAS:
The UNIVARIATE Procedure
Variable: ALTEZZA
Moments
Quantiles (Definition 5)
Quantile Estimate
Extreme Observations
------Lowest----- -----Highest-----
Value Obs Value Obs
57
Stem Leaf # Boxplot
18 0033 4 |
17 5777 4 |
17 00011112334 11 |
16 555555555566666666678888888888899999999 39 |
16 0000000000111111111111122223333333344444 40 +-----+
15 555566666666666666666666677777777777777888999 45 *--+--*
15 00000011111111111222222222222344444444444444 44 | |
14 55556666666667777777777888888999 32 +-----+
14 000000011222223333444444444 27 |
13 56788 5 |
13 0134 4 |
12 8 1 |
----+----+----+----+----+----+----+----+----+
Multiply Stem.Leaf by 10**+1
TABULATE
costruisce tabelle di statistiche descrittive.
CORR
calcola i coefficienti di correlazione fra le variabili.
COMPARE
confronta i valori delle variabili in due Data Set SAS
CONTENTS
scrive descrizioni dei contenuti di uno o più Data Set SAS
COPY
produce copie di una intera (o parti di) una libreria SAS
DATASETS
serve per mettere un Data Set in una libreria
TRANSPOSE
crea un nuovo Data Set SAS invertendo osservazioni con variabili
58
H. ISTRUZIONI E PROCEDURE GRAFICHE
H1. INTRODUZIONE
Gli esempi relativi al modulo SAS/GRAPH utilizzano i dati relativi a studenti dei Corsi di laurea in
Matematica, Informatica e Biologia dell’Università del Piemonte Orientale che hanno frequentato il corso
di Modelli Matematici e Statistici nell’anno accademico 1998/1999.
Di seguito sono riportati il questionario e la codifica delle variabili qualitative.
N. SESSO ALTEZZA PESO CORSO NUMERO COLORE COLORE ATT. DIPLOMA
(M,F) LAUREA SCARPA OCCHI CAPELLI SPORTIVA Superiore
1
- GOUT = nome Catalogo SAS serve per produrre output grafici permanenti
59
PROGRAMMA SAS n. 38:
libname corso 'a:\corsosas';
proc gchart data=corso.mms;
hbar claurea;
vbar claurea;
block claurea;
run;
OUTPUT SAS
60
Principali opzioni per le istruzioni VBAR e HBAR.
DISCRETE
Specifica che la variabile numerica oggetto di analisi assume valori discreti. Se l'opzione non è
presente, la procedura suppone che la variabile assuma valori continui e, in assenza dell'opzione
MIDPOINTS=, vengono scelti i baricentri delle classi rappresentate da barre o settori.
61
GROUP = variabile
produce grafici affiancati, ciascuno dei quali rappresenta le osservazioni che hanno un dato valore
della variabile
PROGRAMMA SAS n. 41:
proc gchart data=corso.mms;
vbar sesso / group = sport discrete;
block sesso / group = sport discrete;
run;
OUTPUT SAS:
SUBGROUP = variabile
suddivide ciascuna barra o blocco in tante parti quanti sono i valori diversi assunti dalla variabile
indicata
62
PATTERNID = SUBGROUP | GROUP | MIDPOINT | BY
specifica di cambiare "disegno" ogni volta che cambiano valore le variabili definite con le opzioni
SUBGROUP, GROUP o MIDPOINT o con l'istruzione BY. Per definire personalmente i "disegni" si
usano le istruzioni PATTERN1 ... PATTERNm
OUTPUT SAS:
Le seguenti due opzioni si usano quando è definita l'opzione GROUP e indicano rispettivamente lo
spazio da lasciare fra le barre dei gruppi e la descrizione dell'asse dei gruppi
- GSPACE = n
- GAXIS = AXISn
63
MIDPOINTS = valori
definisce l'insieme dei punti di mezzo che saranno associati a ciascuna barra o settore della
rappresentazione grafica; detti valori, numerici o alfanumerici, potranno essere elencati secondi le
forme seguenti:
1) una lista di valori numerici, esempio: 5 10 15 20 25 30;
2) una forma ripetitiva del tipo: 5 TO 30 BY 5 che genera i seguenti baricentri con passo 5:
5 10 15 20 25 30;
3) una forma ripetitiva del tipo: 10 TO 1 BY -1 che genera i seguenti baricentri con passo -1:
10 9 8 7 6 5 4 3 2 1;
4) una lista di stringhe racchiuse tra apici del tipo: 'Gennaio' 'Febbraio' 'Marzo' ecc...
64
- TYPE = parola chiave
specifica a cosa deve essere proporzionale la dimensione di ciascuna barra o settore della
rappresentazione grafica; in particolare, parola chiave può essere:
- FREQ la frequenza con cui un valore è stato incontrato
- PERCENT la percentuale di osservazioni che assumono un dato valore
- CFREQ o CPERCENT rispettivamente, la frequenza o la percentuale cumulata
SUM ciascuna barra rappresenta la somma dei valori della variabile
specificata nella opzione SUMVAR=
MEAN il valore medio dei valori della variabile specificata nella opzione
SUMVAR=
SUMVAR = variabile
rappresenta il nome di una variabile i cui valori saranno elaborati in funzione dell'opzione TYPE=.
OUTPUT SAS:
65
LEVELS = n
nel caso che la variabile da rappresentare negli istogrammi assuma valori continui, mediante questa
opzione è possibile specificare che il numero delle barre dell'istogramma dovrà essere n
REF = lista
specifica una lista di linee di riferimento da disegnare sull'asse delle frequenze
SPACE = n
specifica lo spazio fra le barre
WIDTH = n
specifica l'ampiezza delle barre
66
Ulteriori opzioni per VBAR e HBAR:
MISSING
specifica che i valori mancanti devono essere considerati valori validi a cui associare barre o settori.
CAXIS = colore
specifica il colore degli assi
G100
è usata quando è presente l'opzione GROUP e forza le barre al 100 % in ciascun gruppo
LEGEND = LEGENDn
specifica la legenda da associare a ciascun grafico (nel caso in cui sia prevista, ad esempio se è
specificata l'opzione SUBGROUP); l'istruzione LEGENDn deve essere precedentemente definita
NOLEGEND
indica di omettere la legenda usata per ciascun sottogruppo
ASCENDING DESCENDING
indicano di stampa le barre in ordine crescente (risp. decrescente) rispetto alle frequenze
NOZEROS
specifica che ogni barra con valore zero sia soppressa
NOAXIS
sopprime la stampa degli assi
MINOR = n
specifica il numero di tacche piccole da stampare fra le tacche grandi sull'asse delle frequenze
NOSTATS
specifica che nessuna statistica venga stampata in un istogramma a barre orizzontali
FREQ e CFREQ
indicano che siano stampate a lato del grafico le frequenze corrispondenti a ciascuna barra
(con CFREQ le frequenze cumulate)
PERCENT e CPERCENT
indica che siano stampate le percentuali per ciascuna barra (con CPERCENT le percentuali cumulate)
SUM e MEAN
indicano che siano stampati rispettivamente il numero totale di osservazioni per ciascuna barra e la
media delle osservazioni rappresentate da ciascuna barra
NOSYMBOL indica di omettere la legenda dei simboli usati per ciascun sottogruppo
67
H3. LA PROCEDURA GPLOT
La sintassi è la seguente:
PROC GPLOT [opzioni ] ;
Le opzioni della procedura sono:
- DATA = nome Data Set SAS
- ANNOTATE = nome Data Set SAS
- GOUT = nome Catalogo SAS
usati come nella procedura GCHART
- UNIFORM
specifica che la scala sugli assi sia uguale quando è presente l'istruzione BY (per poter confrontare
grafici dei diversi livelli della variabile indicata con BY)
Le principali istruzioni della procedura sono:
Si possono richiedere più grafici contemporaneamente (uno per pagina salvo opzione OVERLAY
indicata sotto).
L'istruzione PLOT2 genera un secondo asse verticale sulla destra dei grafici prodotti con
l'istruzione PLOT. Ha la stessa sintassi della procedura PLOT.
68
Le principali opzioni dell'istruzione PLOT sono:
Opzioni generali:
AREAS = n
specifica quali aree sopra o sotto le linee disegnate devono essere riempite; le aree sono numerate dal
basso in alto (l'area fra l'asse orizzontale e il grafico più "basso" è l'area 1, l' area fra tale grafico e quello
immediatamente più "alto" è l'area 2 e così via); i "disegni" dei ricoprimenti possono essere personalizzati
con le istruzioni PATTERN1 ... PATTERNn.
SKIPMISS crea una interruzione nella linea che unisce i punti quando vi sono dei valori mancanti
AUTOHREF - AUTOVREF
disegna automaticamente linee di riferimento in corrispondenza delle tacche maggiori
HREF = valori - VREF = valori
specifica che una linea orizzontale (risp.verticale) sia disegnata sul grafico all'altezza dei valori indicati
CHREF = colore - CVREF = colore - LHREF = n - LVREF = n
specifica i colori e i caratteri per le linee
GRID produce una "griglia"
NOAXIS
sopprime la stama degli assi, delle etichette e dei valori
CAXIS = colore - CTEXT = colore
specificano il colore rispettivamente della linea degli assi, dei testi sugli assi
HMINOR = n - VMINOR = n
specifica il numero di tacche piccole da disegnare fra le tacche grandi
HZERO VZERO
richiede che le tacche sull'asse verticale (risp. orizzontale) inizino dall'origine
VREVERSE specifica che l'ordine dei valori sull'asse verticale sia invertito
69
H4. ALCUNE ISTRUZIONI PER GLI OUTPUT GRAFICI
Le seguenti istruzioni permettono di personalizzare l'output grafico.
L'istruzione:
GOPTION opzioni ;
permette di impostare il default dell'output grafico.
Deve essere posizionata prima delle procedure grafiche e rimane attiva fino a una dichiarazione
successiva
- per i testi:
CTEXT = colore FTEXT = font HTEXT = n per i testi scritti
(con le istruzioni successive si possono modificare alcuni specifici testi)
- per i titoli:
CTITLE = colore FTITLE = font HTITLE = n per i titoli
(con le istruzioni successive si possono modificare alcuni specifici titoli)
Colori validi:
B blue C cyan W white A gray|grey
R red P pink K black N brown
G green Y yellow M magenta O orange
Le tabelle dei font si trovano alle pagine 166-174 del manuale SAS GRAPH vol.1.
Esempio:
goption device=winprtg
vsize=15 cm
hsize=18 cm
ftext=swiss
htext=1;
70
Le seguenti istruzioni possono essere posizionate sia fuori che dentro le procedure grafiche.
Le seguenti due istruzioni operano come già osservato per gli output non grafici.
La seguente istruzione serve per precisare il "disegno" con cui fare gli istogrammi (linee oblique a
destra, a sinistra, a croce, vuoto, pieno) quando l'istogramma deve essere suddiviso per sottoclassi.
PATTERNn opzioni ;
Alcune opzioni sono:
71
La seguente istruzione serve per precisare i caratteri con cui stampare i grafici e il modo con cui
unire i punti.
SYMBOLn opzioni ;
Alcune opzioni sono:
- per il carattere da plottare in corrispondenza - per il tipo di tratteggio delle linee con cui
dei punti del grafico vanno uniti i punti
V = valore L =n
72
La seguente istruzione serve per precisare come visualizzare gli assi.
AXISn opzioni ;
- per il colore
C = colore
La seguente istruzione serve per precisare l'aspetto delle legende che compaiono nei grafici.
LEGENDn opzioni ;
73
H5. La procedura BOXPLOT:
OUTPT SAS:
74
Un esempio completo di uso della procedura GPLOT:
goption device=winprtg
hsize=18 cm
vsize=25 cm
ftext=swiss
htext=1;
goption reset=(symbol,axis,title);
symbol1 c=blue f=swissb v=-;
symbol2 c=green f=swissb v=@;
symbol3 c=red v=dot;
symbol4 c=pink f=swissb v=x;
symbol5 c=yellow f=swissb v=#;
symbol6 c=cyan f=swissb v=+;
75
data ANNOTA;
set corso.MATP;
x=COL1;
y=COL2;
xsys='2';
ysys='2';
text=_NAME_;
size=1;
label y= 'secondo asse';
label x= 'primo asse';
keep X Y TEXT SIZE XSYS YSYS;
run;
goption reset=(symbol,axis);
symbol1 v=none;
axis1 order=-1 to 1 by 0.2 length=15 cm;
OUTPUT SAS:
76
I. ERRORI E LETTURA DEL LOG
(tratto da SASOnlineDOC)
Types of Errors
Syntax Errors
Syntax errors occur when program statements do not conform to the rules of the SAS language.
Examples of syntax errors include
! misspelling a SAS keyword
! using unmatched quotation marks
! forgetting a semicolon
! specifying an invalid statement option
! specifying an invalid data set option.
When SAS encounters a syntax error, it first attempts to correct the error by attempting to interpret
what you meant, then continues processing your program based on its assumptions. If SAS cannot
correct the error, it prints an error message to the log.
In the following example, the DATA statement is misspelled, and SAS prints a warning message to the
log. Because SAS could interpret the misspelled word, the program runs and produces output.
date temp;
x=1;
run;
77
SAS Log: Syntax Error (misspelled key word)
1 date temp;
----
14
WARNING 14-169: Assuming the symbol DATA was misspelled as date.
2 x=1;
3 run;
4
5 proc print data=temp;
6 run;
Some errors are explained fully by the message that SAS prints in the log; other error messages are not
as easy to interpret because SAS is not always able to detect exactly where the error occurred. For
example, when you fail to end a SAS statement with a semicolon, SAS does not always detect the error
at the point where it occurs because SAS statements are free-format (they can begin and end
anywhere). In the following example, the semicolon at the end of the DATA statement is missing. SAS
prints the word ERROR in the log, identifies the possible location of the error, prints an explanation of
the error, and stops processing the DATA step.
data temp
x=1;
run;
3 run;
NOTE: The SAS System stopped processing this step because of errors.
NOTE: DATA statement used:
real time 0.11 seconds
cpu time 0.02 seconds
4
5 proc print data=temp;
ERROR: File WORK.TEMP.DATA does not exist.
6 run;
NOTE: The SAS System stopped processing this step because of errors.
NOTE: PROCEDURE PRINT used:
real time 0.06 seconds
cpu time 0.01 seconds
Whether subsequent steps are executed depends on which method of running SAS you use, as well as
on your operating environment.
78
Semantic Errors
Semantic errors occur when the form of the elements in a SAS statement is correct, but the elements
are not valid for that usage. Semantic errors are detected at compile time and can cause SAS to enter
syntax check mode.
Examples of semantic errors include
! specifying the wrong number of arguments for a function
! using a numeric variable name where only a character variable is valid
! using illegal references to an array.
In the following example, SAS detects an illegal reference to the array ALL.
data _null_;
array all{*} x1-x5;
all=3;
datalines;
1 1.5
. 3
2 4.5
3 2 7
3 . .
;
run;
1 data _null_;
2 array all{*} x1-x5;
ERROR: Illegal reference to the array all.
3 all=3;
4 datalines;
NOTE: The SAS System stopped processing this step because of errors.
NOTE: DATA statement used:
real time 2.28 seconds
cpu time 0.06 seconds
10 ;
11
The following is another example of a semantic error. In this DATA step, the libref SOMELIB has not
been previously assigned in a LIBNAME statement.
data test;
set somelib.old;
run;
1 data test;
ERROR: Libname SOMELIB is not assigned.
2 set somelib.old;
3 run;
NOTE: The SAS System stopped processing this step because of errors.
WARNING: The data set WORK.TEST may be incomplete. When this step was stopped
there were 0 observations and 0 variables.
NOTE: DATA statement used:
real time 0.17 seconds
79
Execution-Time Errors
Definition
Execution-time errors occur when SAS executes a program that contains data values. Most execution-
time errors produce warning messages or notes in the SAS log but allow the program to continue
executing. (footnote 1)The location of an execution-time error is usually given as line and column
numbers in a note or error message.
Common execution-time errors include the following:
! illegal arguments to functions
! illegal mathematical operations (for example, division by 0)
! observations in the wrong order for BY-group processing
! reference to a nonexistent member of an array (occurs when the array's subscript is out of
range)
! open and close errors on SAS data sets and other files in INFILE and FILE statements
! INPUT statements that do not match the data lines (for example, an INPUT statement in which
you list the wrong columns for a variable or fail to indicate that the variable is a character
variable).
Out-of-Resources Condition
An execution-time error can also occur when you encounter an out-of-resources condition, such as a full
disk, or insufficient memory for a SAS procedure to complete. When these conditions occur, SAS
attempts to find resources for current use. For example, SAS may ask the user for permission to delete
temporary data sets that might no longer be needed, or to free the memory in which macro variables
are stored.
When an out-of-resources condition occurs in a windowing environment, you can use the SAS CLEANUP
system option to display a requestor panel that enables you to choose how to resolve the error. When
you run SAS in batch, noninteractive, or interactive line mode, the operation of CLEANUP depends on
your operating environment. For more information about this system option, see CLEANUP in the "SAS
System Options" chapter in SAS Language Reference: Dictionary, and in the SAS documentation for
your operating environment.
Examples
In the following example, an execution-time error occurs when SAS uses data values from the second
observation to perform the division operation in the assignment statement. Division by 0 is an illegal
mathematical operation and causes an execution-time error.
data inventory;
input Item $ 1-14 TotalCost 15-20
UnitsOnHand 21-23;
UnitCost=TotalCost/UnitsOnHand;
datalines;
Hammers 440 55
Nylon cord 35 0
Ceiling fans 1155 30
;
proc print data=inventory;
format TotalCost dollar8.2 UnitCost dollar8.2;
run;
1
2 options linesize=64 nodate pageno=1 pagesize=25;
3
80
4 data inventory;
5 input Item $ 1-14 TotalCost 15-20
6 UnitsOnHand 21-23;
7 UnitCost=TotalCost/UnitsOnHand;
8 datalines;
NOTE: Division by zero detected at line 12 column 22.
RULE:----+----1----+----2----+----3----+----4----+----5----+----
10 Nylon cord 35 0
Item=Nylon cord TotalCost=35 UnitsOnHand=0 UnitCost=. _ERROR_=1
_N_=2
NOTE: Mathematical operations could not be performed at the
following places. The results of the operations have been
set to missing values.
Each place is given by:
(Number of times) at (Line):(Column).
1 at 12:22
NOTE: The data set WORK.INVENTORY has 3 observations and 4
variables.
NOTE: DATA statement used:
real time 2.78 seconds
cpu time 0.08 seconds
12 ;
13
14 proc print data=inventory;
15 format TotalCost dollar8.2 UnitCost dollar8.2;
16 run;
NOTE: There were 3 observations read from the dataset
WORK.INVENTORY.
NOTE: PROCEDURE PRINT used:
real time 2.62 seconds
Total Units
Obs Item Cost OnHand UnitCost
SAS executes the entire step, assigns a missing value for the variable UnitCost in the output, and writes
the following to the SAS log:
! a note
! the values stored in the input buffer
! the contents of the program data vector at the time the error occurred
! a note explaining the error.
Note that the values listed in the program data vector include the _N_ and _ERROR_ automatic
variables. These automatic variables are assigned temporarily to each observation and are not stored
with the data set.
In the following example of an execution-time error, the program processes an array and SAS
encounters a value of the array's subscript that is out of range. SAS prints an error message to the log
and stops processing.
data test;
array all{*} x1-x3;
input I measure;
if measure > 0 then
81
all{I} = measure;
datalines;
1 1.5
. 3
2 4.5
;
12 ;
13
14 proc print data=test;
15 run;
NOTE: There were 1 observations read from the dataset WORK.TEST.
NOTE: PROCEDURE PRINT used:
real time 0.81 seconds
Data Errors
Data errors occur when some data values are not appropriate for the SAS statements that you have
specified in the program. For example, if you define a variable as numeric, but the data value is actually
character, SAS generates a data error. SAS detects data errors during program execution and continues
to execute the program, and does the following:
! writes an invalid data note to the SAS log.
! prints the input line and column numbers that contain the invalid value in the SAS log.
Unprintable characters appear in hexadecimal. To help determine column numbers, SAS prints a
rule line above the input line.
! prints the observation under the rule line.
! sets the automatic variable _ERROR_ to 1 for the current observation.
In this example, a character value in the Number variable results in a data error during program
execution:
82
data age;
input Name $ Number;
datalines;
Sue 35
Joe xx
Steve 22
;
1
2 options linesize=64 nodate pageno=1 pagesize=25;
3
4 data age;
5 input Name $ Number;
6 datalines;
NOTE: Invalid data for Number in line 61 5-6.
RULE:----+----1----+----2----+----3----+----4----+----5----+----
8 Joe xx
Name=Joe Number=. _ERROR_=1 _N_=2
NOTE: The data set WORK.AGE has 3 observations and 2 variables.
NOTE: DATA statement used:
real time 0.06 seconds
cpu time 0.02 seconds
10 ;
11
12 proc print data=age;
13 run;
NOTE: There were 3 observations read from the dataset WORK.AGE.
NOTE: PROCEDURE PRINT used:
real time 0.01 seconds
1 Sue 35
2 Joe .
3 Steve 22
You can also use the INVALIDDATA= system option to assign a value to a variable when your program
encounters invalid data. For more information, see the INVALIDDATA= system option in SAS Language
Reference: Dictionary.
83
! _error_=0;
In either case, iSAS sets the invalid values of X to missing values.
Macro-related Errors
Several types of macro-related errors exist:
! macro compile time and macro execution-time errors, generated when you use the macro facility
itself
! errors in the SAS code produced by the macro facility.
For more information about macros, see SAS Macro Language: Reference.
FOOTNOTE 1: When you run SAS in noninteractive mode, more serious errors can cause SAS to enter
syntax check mode and stop processing the program.
Error Processing
Syntax Check Mode
If a DATA step has a syntax error, SAS can enter syntax check mode. SAS internally sets the OBS=
option to 0 and the REPLACE/NOREPLACE option to NOREPLACE. When these options are in effect, SAS
! reads the remaining statements in the DATA step
! checks that statements are valid SAS statements
! executes global statements
! identifies any other errors that it finds
! creates the descriptor portion of any output data sets that are specified in program statements
! does not write any observations to new data sets that SAS creates
! does not execute most of the subsequent DATA steps or procedures in the program (exceptions
include PROC DATASETS and PROC CONTENTS).
Note: Any data sets that are created after SAS has entered syntax check mode do not replace existing
data sets with the same name.
data temporary;
Item1=4;
run;
84
SAS Log: Multiple Program Errors
cpu time 0.00 seconds
1 data temporary;
2 Item1=4;
3 run;
NOTE: The data set WORK.TEMPORARY has 1 observations and 1
variables.
NOTE: DATA statement used:
real time 0.10 seconds
cpu time 0.01 seconds
4
5 proc print data=temporary;
ERROR: Variable ITEM2 not found.
ERROR: Variable ITEM3 not found.
6 var Item1 Item2 Item3;
7 run;
NOTE: The SAS System stopped processing this step because of
errors.
NOTE: PROCEDURE PRINT used:
real time 0.53 seconds
cpu time 0.01 seconds
SAS displays two error messages, one for the variable Item2 and one for the variable Item3.
When running debugged production programs that are unlikely to encounter errors, you may want to
force SAS to abend after a single error occurs. You can use the ERRORABEND system option to do this.
85
J. APPROFONDIMENTI: MANIPOLAZIONE DI DATA SET SAS
!
7()'#/'-@4($!
The following figure shows the
results of interleaving two SAS data
sets. Interleaving intersperses
observations from two or more data
sets, based on one or more common
variables. Data set COMBINED
shows the result.
!
86
A('B)DBA('!G'-M4($!-(M!
A('B)DBA('!H'#$4($!
The following figure shows the
results of one-to-one reading and
one-to-one merging. One-to-one
reading combines observations from
two or more SAS data sets by
creating observations that contain all
of the variables from each
contributing data set. Observations
are combined based on their relative
position in each data set, that is, the
first observation in one data set with
the first in the other, and so on. The
DATA step stops after it has read the
last observation from the smallest
data set. One-to-one merging is
similar to a one-to-one reading, with
two exceptions: you use the MERGE !
statement instead of multiple SET
statements, and the DATA step reads
all observations from all data sets.
Data set COMBINED shows the
result.
H-)9=BH'#$4($!
The following figure shows the
results of match-merging. Match-
merging combines observations from
two or more SAS data sets into a
single observation in a new data set
based on the values of one or more
common variables. Data set
COMBINED shows the results.
!
87
?.M-)4($!
88
J2. MANIPOLAZIONE DI DATA SET SAS
J2.1. PER CONCATENARE I DSS: USO DI SET
I DSS sono concatenati uno dietro l’altro secondo l’ordine con cui sono scritti nell’istruzione SET.
Il DSS costruito ha l’unione delle variabili dei DSS di partenza e un numero di osservazioni pari alla
somma del numero di osservazioni dei DSS di partenza.
89
J2.2. PER INTERCALARE I DSS: USO DI SET – BY E DI MERGE – BY
La sintassi è:
data DSS; data DSS;
set nome-DSS1 nome-DSS2; merge nome-DSS1 nome-DSS2;
BY nome-var; BY nome-var;
Nel DSS costruito le osservazioni dei DSS di Nel DSS costruito le osservazioni dei DSS di
partenza sono intercalate le une alle altre partenza sono COMBINATE in una sola
secondo la variabile BY: il numero delle osservazione secondo la variabile BY.
osservazioni è uguale quindi alla somma del Il numero di osservazioni del DSS finale è
numero delle osservazioni dei DSS di partenza. uguale alla somma del numero massimo di
osservazioni della variabile BY in tutti i DSS.
Il valore di ciascuna variabile è “ritenuto” fino a
quando non sono state scritte tutte le
osservazioni della variabile BY.
90
DSS Animali_nr DSS Piante_nr
a Antilope 5 a Ananas 29
b Balena . b Banano 25
c Canguro 7 c Cocco .
d Dattero 24
e Ebano 25
a Antilope 5 a Ananas 29
a Ariete . b Banano 25
b Balena 3 c Cocco .
c Canguro 7 c Ciliegio 27
d Dattero 24
e Ebano 25
91
J2.3. PER “AFFIANCARE” DSS CON VARIABILI DIVERSE: USO DI SET – SET E DI
MERGE
La sintassi è:
data DSS; data DSS;
set nome-DSS1; merge nome-DSS1 nome-DSS2;
set nome-DSS2;
Le variabili del DSS2 vengono sovrapposte a quelle del DSS1. Se le variabili del DD2 sono mancanti
vengono lasciati i valori del DSS1. Più precisamente. Viene letta la prima osservazione dal DSS1 poi la
prima osservazione dal secondo DSS2: se entrambi i DSS contengono le stesse variabili il valore del
DSS1 è sostituito da quello del DSS2, anche se il valore è missing.
Il DSS costruito ha un numero di osservazioni pari Il DSS costruito ha un numero di osservazioni pari
al numero MINIMO di osservazioni dei due DSS di al numero MASSIMO di osservazioni dei due DSS di
partenza. partenza.
PRIMO CASO: Le osservazioni sono scritte nello stesso ordine nei due DSS da affiancare (fra i nostri
esempi consideriamo quei DSS che non hanno osservazioni ripetute).
a Antilope 5 a Ananas 29
b Balena . b Banano 25
c Canguro 7 c Cocco .
d Dattero 24
e Ebano 25
92
SECONDO CASO: Le osservazioni NON sono scritte nello stesso ordine nei due DSS da affiancare (fra i
nostri esempi consideriamo quei DSS che hanno osservazioni ripetute).
93
J2.4. PER AGGIORNARE UN DSS: USO DI UPDATE
94
J2.5 PER AGGIUNGERE OSSERVAZIONI A UN DSS: LA PROC
APPEND
La sintassi della procedura è la seguente:
Il DSS principale è quello a cui si vogliono aggiungere osservazioni, che sono contenute nel DSS di
transizione.
Le variabili del DSS di transizione non contenute già nel DSS principale vengono ignorate.
Se le variabili sono le stesse nei due DSS, la Proc Append e l’istruzione SET producono un risultato
analogo: se il DSS principale è molto grande può essere più efficiente usare la procedura APPEND che
usare l’istruzione SET.
Attenzione: il DSS principale viene modificato; può essere opportuno fare una copia del DSS principale.
95
J3. OSSERVAZIONI RAGGRUPPATE:
USO DI SET – BY E VARIABILI FIRST.<..> E LAST.<..>
Understanding BY Groups
BY Groups with a Single BY Variable
The following figure represents the results of processing your data with the single BY variable ZipCode.
The input SAS data set contains street names, cities, states, and ZIP codes that are arranged in an order
that you can use with the following BY statement:
by ZipCode;
The figure shows five BY groups each containing the BY variable ZipCode. The data set is shown with
the BY variable ZipCode printed on the left for easy reading, but the position of the BY variable in the
observations does not matter.
BY Groups for the Single BY Variable ZipCode
The first BY group contains all observations with the smallest BY value, which is 33133; the second BY
group contains all observations with the next smallest BY value, which is 33146, and so on.
96
BY Groups for the BY Variables State and City
The observations are arranged so that the observations for Arizona occur first. The observations within
each value of State are arranged in order of the value of City. Each BY group has a unique combination
of values for the variables State and City. For example, the BY value of the first BY group is AZ Tucson,
and the BY value of the second BY group is FL Lakeland.
Invoking BY-Group Processing
You can invoke BY-group processing in both DATA steps and PROC steps by using a BY statement. For
example, the following DATA step program uses the SET statement to combine observations from three
SAS data sets by interleaving the files. The BY statement shows how the data is ordered.
data all_sales;
set region1 region2 region3;
by State City Zip;
... more SAS statements ...
run;
This section describes BY-group processing for the DATA step. For information on BY-group processing
with procedures, see the SAS Procedures Guide.
How the DATA Step Identifies BY Groups
In the DATA step, SAS identifies the beginning and end of each BY group by creating two temporary
variables for each BY variable: FIRST.variable and LAST.variable. These temporary variables are
available for DATA step programming but are not added to the output data set. Their values indicate
whether an observation is
! the first one in a BY group
! the last one in a BY group
! neither the first nor the last one in a BY group
! both first and last, as is the case when there is only one observation in a BY group.
You can take actions conditionally, based on whether you are processing the first or the last observation
of a BY group.
When an observation is the first in a BY group, SAS sets the value of the FIRST.variable to 1. For all
other observations in the BY group, the value of the FIRST.variable is 0. Likewise, if an observation is
97
the last in a BY group, SAS sets the value of LAST.variable to 1. For all other observations in the BY
group, the value of LAST.variable is 0. If the observations are sorted by more than one BY variable, the
FIRST.variable for each variable in the BY statement is set to 1 at the first occurrence of a new value for
the variable.
This example shows how SAS uses the FIRST.variable and LAST.variable to flag the beginning and
end of four BY groups. Six temporary variables are created within the program data vector. These
variables can be used during the DATA step, but they do not become variables in the new data set.
In the figure that follows, observations in the SAS data set are arranged in an order that can be used with
this BY statement:
by State City ZipCode;
SAS creates the following temporary variables: FIRST.State, LAST.State, FIRST.City, LAST.City,
FIRST.ZipCode, and LAST.ZipCode.
FIRST. and LAST. Values for Four BY Groups
ESEMPIO
L’esempio è riferito a un insieme di dati clinici; della maggior parte dei pazienti vengono fatte più
rilevazioni in epoche successive: la variabile “giorno” indica il conteggio dei giorni dall’inizio dello
studio clinico. La variabile “paziente” indica il numero che identifica il paziente
Il seguente programma costruisce un DSS con una variabile contenente il numero di rilevazioni per
ciascun paziente.
data numero;
set tp1.cirr_seq;
by id;
retain num_oss;
if first.id =1 then num_oss =0;
num_oss =num_oss +1;
if last.id=1 then output;
keep id num_oss;
98
K. APPROFONDIMENTI: LETTURA DI DATI GREZZI
Abbiamo già visto tre tipi di input
! a lista
! a column
! a formato
In questi approfondimenti ne esamineremo altri due:
! a lista con formato
! con nome
ESEMPIO di uso di : e ~
data scores;
infile datalines dsd;
input Name : $9. Score1-Score3 Team ~ $25. Div $;
datalines;
Smith,12,22,46,"Green Hornets, Atlanta",AAA
Mitchel,23,19,25,"High Volts, Portland",AAA
Jones,09,17,54,"Vulcans, Las Vegas",AA
;
proc print data=scores noobs;
run;
OUTPUT SAS
99
K2. INPUT CON NOME
Serve per leggere dati in cui i valori sono preceduti dal nome della variabile e dal segno uguale (=)
data games;
input name=$ score1= score2=;
datalines;
name=riley score1=1132 score2=1187
;
N;O!IAIE+8I7A8+!2+CCP !78E?Q1!?IA!27!R
@ holds an input record for the execution of the next INPUT statement within the same iteration of
the DATA step. This line-hold specifier is called trailing @.
Restriction: The trailing @ must be the last item in the INPUT statement.
Tip: The trailing @ prevents the next INPUT statement from automatically releasing
the current input record and reading the next record into the input buffer. It
is useful when you need to read from a record multiple times.
+,-&./'1!SD/M4($!-!G'9D#M!4(!)='!7(.%)!T%33'#!!
This example reads a file that contains two kinds of input data records and creates a SAS data set from
these records. One type of data record contains information about a particular college course. The second
type of record contains information about the students enrolled in the course. You need two INPUT
statements to read the two records and to assign the values to different variables that use different
formats. Records that contain class information have a C in column 1; records that contain student
information have an S in column 1, as shown here:
----+----1----+----2----+
C HIST101 Watson
S Williams 0459
S Flores 5423
C MATH202 Sen
S Lee 7085
To know which INPUT statement to use, check each record as it is read. Use an INPUT statement that
reads only the variable that tells whether the record contains class or student.
data schedule(drop=type);
infile file-specification;
retain Course Professor;
input type $ 1 @;
if type='C' then
input course $ professor $;
else if type='S' then
do;
input Name $10. Id;
output schedule;
end;
proc print; run;
The first INPUT statement reads the TYPE value from column 1 of every line. Because this INPUT
statement ends with a trailing @, the next INPUT statement in the DATA step reads the same line. The
IF-THEN statements that follow check whether the record is a class or student line before another INPUT
statement reads the rest of the line. The INPUT statements without a trailing @ release the held line. The
100
RETAIN statement saves the values about the particular college course. The DATA step writes an
observation to the SCHEDULE data set after a student record is read.
The following output that PROC PRINT generates shows the resulting data set SCHEDULE.
The SAS System 1
+,-&./'1!ED*4)4D(4($!)='!ED4()'#!U4)=!-!8%&'#49!:-#4-L/'!!
This example uses a numeric variable to position the pointer. A raw data file contains records with the
employment figures for several offices of a multinational company. The input data records are
----+----1----+----2----+----3----+
8 New York 1 USA 14
5 Cary 1 USA 2274
3 Chicago 1 USA 37
22 Tokyo 5 ASIA 80
5 Vancouver 2 CANADA 6
9 Milano 4 EUROPE 123
The first column has the column position for the office location. The next numeric column is the region
category. The geographic region occurs before the number of employees in that office.
You determine the office location by combining the @numeric-variable pointer control with a trailing
@. To read the records, use two INPUT statements. The first INPUT statement obtains the value for the
@ numeric-variable pointer control. The second INPUT statement uses this value to determine the
column that the pointer moves to.
data office (drop=x);
infile file-specification;
input x @;
if 1<=x<=10 then
input @x City $9.;
else do;
put 'Invalid input at line ' _n_;
delete;
end;
run;
The DATA step writes only five observations to the OFFICE data set. The fourth input data record is
invalid because the value of X is greater than 10. Therefore, the second INPUT statement does not
execute. Instead, the PUT statement writes a message to the SAS log and the DELETE statement stops
processing the observation.
101
K4. OPZIONI DI INFILE PER LEGGERE DATI CON DELIMITATORI
NELL’INPUT A LISTA
By default, the delimiter to read input data records with list input is a blank space. Both the DSD option
and the DELIMITER= option affect how list input handles delimiters. The DELIMITER= option
specifies that the INPUT statement use a character other than a blank as a delimiter for data values that
are read with list input. When the DSD option is in effect, the INPUT statement uses a comma as the
default delimiter.
To read a value as missing between two consecutive delimiters, use the DSD option. By default, the
INPUT statement treats consecutive delimiters as a unit. When you use DSD, the INPUT statement treats
consecutive delimiters separately. Therefore, a value that is missing between consecutive delimiters is
read as a missing value. To change the delimiter from a comma to another value, use the DELIMITER=
option.
For example, this DATA step program uses list input to read data that are separated with commas. The
second data line contains a missing value. Because SAS allows consecutive delimiters with list input, the
INPUT statement cannot detect the missing value.
data scores;
infile datalines delimiter=',';
input test1 test2 test3;
datalines;
91,87,95
97,,92
,1,1
;
+,-&./'!01!<=-($4($!SDU!2'/4&4)'#*!-#'!Q#'-)'M!!
By default, the INPUT statement uses a blank as the delimiter. This DATA step uses a comma as the delimiter:
data num;
infile datalines dsd;
input x y z;
datalines;
,2,3
4,5,6
7,8,9
;
The argument DATALINES in the INFILE statement allows you to use an INFILE statement option to
read in-stream data lines. The DSD option sets the comma as the default delimiter. Because a comma
precedes the first value in the first dataline, a missing value is assigned to variable X in the first
observation, and the value 2 is assigned to variable Y.
102
If the data uses multiple delimiters or a single delimiter other than a comma, simply specify the delimiter
values with the DELIMITER= option. In this example, the characters a and b function as delimiters:
data nums;
infile datalines dsd delimiter='ab';
input X Y Z;
datalines;
1aa2ab3
4b5bab6
7a8b9
;
The output that PROC PRINT generates shows the resulting NUMS data set. Values are missing for
variables in the first and second observation because DSD causes list input to detect two consecutive
delimiters. If you omit DSD, the characters a, b, aa, ab, ba, or bb function as the delimiter and no
variables are assigned missing values.
The SAS System 1
OBS X Y Z
1 1 . 2
2 4 5 .
3 7 8 9
This DATA step uses modified list input and the DSD option to read data that are separated by commas
and that may contain commas as part of a character value:
data scores;
infile datalines dsd;
input Name : $9. Score
Team : $25. Div $;
datalines;
Joseph,76,"Red Racers, Washington",AAA
Mitchel,82,"Blue Bunnies, Richmond",AAA
Sue Ellen,74,"Green Gazelles, Atlanta",AA
;
The output that PROC PRINT generates shows the resulting SCORES data set. The delimiter (comma) is
stored as part of the value of TEAM while the quotation marks are not. The folowing output shows how
to use the tilde (~) format modifier in an INPUT statement to retain the quotation marks in character data.
OBS NAME SCORE TEAM DIV
1 Joseph 76 Red Racers, Washington AAA
2 Mitchel 82 Blue Bunnies, Richmond AAA
3 Sue Ellen 74 Green Gazelles, Atlanta AA
103
K5. Valori Missing particolari
Is a type of numeric missing value that enables you to represent different categories of missing data by
using the letters A-Z or an underscore.
Example
The following example uses data from a marketing research company. Five testers were hired to test five
different products for ease of use and effectiveness. If a tester was absent, there is no rating to report, and
the value is recorded with an X for "absent." If the tester was unable to test the product adequately, there
is no rating, and the value is recorded with an I for "incomplete test." The following program reads the
data and displays the resulting SAS data set. Note the special missing values in the first and third data
lines:
data period_a;
missing X I;
input Id $4. Foodpr1 Foodpr2 Foodpr3 Coffeem1 Coffeem2;
datalines;
1001 115 45 65 I 78
1002 86 27 55 72 86
1004 93 52 X 76 88
1015 73 35 43 112 108
1027 101 127 39 76 79
;
proc print data=period_a;
title 'Results of Test Period A';
footnote1 'X indicates TESTER ABSENT';
footnote2 'I indicates TEST WAS INCOMPLETE';
run;
The following output is produced:
1 1001 115 45 65 I 78
2 1002 86 27 55 72 86
3 1004 93 52 X 76 88
4 1015 73 35 43 112 108
5 1027 101 127 39 76 79
104
L. APPROFONDIMENTI: FORMATI DI LETTURA E
SCRITTURA DEI DATI
In a The ATTRIB and INFORMAT Use the ATTRIB statement or the FORMAT
PROC statements are valid in base SAS statement to associate formats with variables. If you
step! procedures. However, in base SAS use either statement in a procedure that produces an
software, typically you do not assign output data set, the format is permanently associated
informats in PROC steps because the with the variable in the output data set. If you use
data have already been read into SAS either statement in a procedure that does not
variables. ! produce an output data set, the statement associates
the format with the variable only for the duration of
the PROC step. !
105
L1. ISTRUZIONE FORMAT
Un FORMAT è un’istruzione che SAS usa per scrivere i valori dei dati. Si usa l’istruzione FORMAT per
controllare l’aspetto dei dati o, in alcuni casi, per raggruppare i dati da analizzare. Per esempio, il format
WORDS22, che converte i valori numerici nella corrispondente versione in lettere (in inglese), scrive il
valore numerico 692 come six hundred ninety-two.
La sintassi è <$>format<w>.<d>
OSSERVAZIONE:
In entrambi i casi la lunghezza della variabile rimane quella originale.
106
L2. ISTRUZIONE INFORMAT
Un INFORMAT è un’istruzione che SAS usa per leggere e assegnare a una variabile i valori dei dati.
Per esempio il seguente valore contiene un segno di dollaro e alcune virgole:
$1,000,000
Per rimuovere il segno di dollaro ($) e le virgole (,) prima di memorizzare il valore numerico 1000000 in
una variabile, bisogna leggere questo valore con l’informat COMMA11. .
Se non si definisce esplicitamente una variabile precedentemente, SAS usa l’informat per determinare se
la variabile è numerica o carattere e per determinare la lunghezza di una variabile carattere.
La sintassi è la seguente:
<$>informat<w>.<d
>!
Informat per categoria
CHARACTER instructs SAS to read character data values into character variables.
COLUMN-BINARY instructs SAS to read data stored in column-binary or multipunched form into
character and numeric variables.
DATE and TIME instructs SAS to read data values into variables that represent dates, times, and
datetimes.
NUMERIC instructs SAS to read numeric data values into numeric variables.
USER-DEFINED instructs SAS to read data values by using an informat that is created with an
INVALUE statement in PROC FORMAT.
107
ALCUNE DEI PRINCIPALI INFORMAT E FORMAT
PER LE VARIABILI CARATTERE, NUMERICHE E PER DATE E TEMPI
Categories and Descriptions of Informats
Category Informat Description
Character $CHARw. Reads/Writes character data with blanks
$CHARZBw. Converts binary 0s to blanks
$QUOTEw. Removes matching quotation marks from character data
$REVERJw. Reads/Writes character data from right to left and preserves blanks
$REVERSw. Reads/Writes character data from right to left and left aligns
$UPCASEw. Converts character data to uppercase
$VARYINGw. Reads/Writes character data of varying length
$w. Reads/Writes standard character data
Date and Time DATEw. Reads/Writes date values in the form ddmmmyy or ddmmmyyyy
DATETIMEw. Reads/Writes datetime values in the form ddmmmyy hh:mm:ss.ss or
ddmmmyyyy hh:mm:ss.ss
DDMMYYw. Reads/Writes date values in the form ddmmyy or ddmmyyyy
MMDDYYw. Reads/Writes date values in the form mmddyy or mmddyyyy
MONYYw. Reads/Writes month and year date values in the form mmmyy or mmmyyyy
TIMEw. Reads/Writes hours, minutes, and seconds in the form hh:mm:ss.ss
YYMMDDw. Reads/Writes date values in the form yymmdd or yyyymmdd
YYMMNw. Reads/Writes date values in the form yyyymm or yymm
YYQw. Reads/Writes quarters of the year
Numeric COMMAw.d Removes embedded characters
COMMAXw.d Removes embedded characters
Ew.d Reads/Writes numeric values that are stored in scientific notation and double-
precision scientific notation
FLOATw.d Reads/Writes a native single-precision, floating-point value and divides it by
10 raised to the dth power
HEXw. Converts hexadecimal positive binary values to either integer (fixed-point) or
real (floating-point) binary values
NUMXw.d Reads/Writes numeric values with a comma in place of the decimal point
PERCENTw.d Reads/Writes percentages as numeric values
w.d Reads/Writes standard numeric data
YENw.d Removes embedded yen signs, commas, and decimal points
ZDw.d Reads/Writes zoned decimal data
ZDBw.d Reads/Writes zoned decimal data in which zeros have been left blank
ZDVw.d Reads/Writes and validates zoned decimal data
108
L3. ISTRUZIONE LENGTH
Specifica il numero di byte che SAS usa per immaganizzare i valori delle variabili. Si può usare solo in un
passo di Data.
La sintassi è:
Per modificare la lunghezza di una variabile di un DSS già esistente bisogna mettere
l’istruzione prima che il DSS sia dichiarato (con set, merge, ...).
Ambiente: passo di data
1-modifica modifica della lunghezza di una variabile carattere
109
L4. ISTRUZIONE ATTRIB
!
Associates a format, informat, label, and/or length with one or more variables
Syntax
ATTRIB variable-list(s) attribute-list(s)
;!
"#$%&'()*!
variable-list
names the variables that you want to associate with the attributes.
Tip:! List the variables in any form that SAS
allows.!
attribute-list
specifies one or more attributes to assign to variable-list. Specify one or more of these attributes
in the ATTRIB statement:
FORMAT=format
associates a format with variables in variable-list.
Tip:! The format can be either a standard SAS format or a format that is defined with the
FORMAT procedure.!
INFORMAT=informat
associates an informat with variables in variable-list.
Tip:! The informat can be either a standard SAS informat or an informat that is defined
with the FORMAT procedure.!
LABEL='label'
associates a label with variables in variable-list.
LENGTH=<$>length
specifies the length of variables in variable-list.
Requirement Put a dollar sign ($) in front of the length of character variables.!
:!
Tip:! Use the ATTRIB statement before the SET statement to change the length of
variables in an output data set when you use an existing data set as input.!
Range:! For character variables, the range is 1 to 32,767 for all operating environments.
Operating Environment Information: For numeric variables, the minimum
length you can specify with the LENGTH= specification is 2 in some operating
environments and 3 in others.
!
Details!
!
Q='!T-*49*!
Using the ATTRIB statement in the DATA step permanently associates attributes with variables by
changing the descriptor information of the SAS data set that contains the variables.
You can use ATTRIB in a PROC step, but the rules are different.
110
SDU!I"I!Q#'-)*!:-#4-L/'*!U='(!VD%!"**4$(!7(3D#&-)*!U4)=!)='!78WAGH"QX!A.)4D(!
D(!)='!"QQG7T!I)-)'&'()!
Informats that are associated with variables by using the INFORMAT= option on the ATTRIB statement
behave like informats that are used with modified list input. SAS reads the variables by using the
scanning feature of list input, but applies the informat. In modified list input, SAS
! does not use the value of w in an informat to specify column positions or input field widths in an
external file
! uses the value of w in an informat to specify the length of previously undefined character
variables
! ignores the value of w in numeric informats
! uses the value of d in an informat in the same way it usually does for numeric informats
! treats blanks that are embedded as input data as delimiters unless you change their status with a
DELIMITER= option specification in an INFILE statement.
If you have coded the INPUT statement to use another style of input, such as formatted input or column
input, that style of input is not used when you use the INFORMAT= option on the ATTRIB statement.
Comparisons!
You can use either an ATTRIB statement or an individual attribute statement such as FORMAT,
INFORMAT, LABEL, and LENGTH to change an attribute that is associated with a variable.
Examples!
Here are examples of ATTRIB statements that contain
! single variable and single attribute:
attrib cost length=4;
! single variable with multiple attributes:
attrib saleday informat=mmddyy.
format=worddate.;
! multiple variables with the same multiple attributes:
attrib x y length=$4 label='TEST VARIABLE';
! multiple variables with different multiple attributes:
attrib x length=$4 label='TEST VARIABLE'
y length=$2 label='RESPONSE';
! variable list with single attribute:
attrib month1-month12
label='MONTHLY SALES';
111
L5. PROC FORMAT
L5.1. Istruzione VALUE
Si costruisce una etichetta permanente nella sessione aperta
data pluto3;
set pippo2; # Variable Type Len Pos Format
format x P. a C.; ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ
1 a Char 8 8 $C.
2 x Num 8 0 P.
112
L5.2. Istruzione INVALUE
1 - da carattere a numero
2 - da numero a carattere
Obs a x
proc format;
invalue $ fc low-53='basso' 1 m alto
2 f basso
53-high='alto';
3 m basso
data pippo;
length x $ 6;
input a $ x $ fc.; The CONTENTS Procedure
datalines; ...
m 55 ----Alphabetic List of Variables and Attributes-----
f 52
m 53 # Variable Type Len Pos
; ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ
run; 1 a Char 8 0
2 x Char 6 8
113
L5.3. Istruzione PICTURE (SCRITTURA DI VARIABILI NUMERICHE )
data pippo;
input a b: ddmmyy. c;
datalines;
21111.5 12/05/01 1213344
3.8 13/12/02 1223
;
proc format;
picture separa low-high='000,000.000' (dig3sep=',' decsep='.') ;
picture sep low-high='000@000&000' (dig3sep='@' decsep='&') ; /*un po strano*/
picture data (default=20) low-high='%A,%d/%m/%Y'(datatype=date);
picture doll low-high='000,000,000' (dig3sep=','prefix='$ ');
run;
! Specify multiple pictures for a given value or range and for overlapping MULTILABEL
ranges!
! Store values or ranges in the order that you define them! NOTSORTED!
114
Control the attributes of each picture in the format! !
! Specify a character that completes the formatted value! FILL=!
! Specify that numbers are message characters rather than digit selectors! NOEDIT!
115
L5.4. Riassunto: alcuni esempi di cambio di formati
2
- da numero a carattere
116
B. CAMBIO DI FORMATO LEGGENDO I DATI DA UN DSS
data pippo2;
input a $ x;
datalines;
mnopqr 55
fghilm 52
mnopqr 53
;
data pluto;
set pippo2;
attrib x format= 5.1;
The CONTENTS Procedure
...
----Alphabetic List of Variables and Attributes-----
Obs a x
data pluto2;
set pippo2;
attrib a format= $3.; The CONTENTS Procedure
...
----Alphabetic List of Variables and Attributes-----
Obs a x
# Variable Type Len Pos Format
1 mno 55 ƒƒƒƒ ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ
2 fgh 52 1 a Char 8 8 $3.
3 mno 53 2 x Num 8 0
data pluto2;
set pippo2;
attrib a format= $3.;
The CONTENTS Procedure
...
----Alphabetic List of Variables and Attributes-----
Obs a x
117
L5.5. FUNZIONI DI CONVERSIONE DA VARIABILE CARATTERE A
NUMERICA E VICEVERSA
"#$%&'()*!
source
identifies the SAS variable or constant whose value you want to reformat. The source argument can
be character or numeric.
format.
contains the SAS format that you want applied to the variable or constant that is specified in the
source. To override the default alignment, you can add an alignment specification to a format:
-L left aligns the value.
-C centers the value.
-R right aligns the value.
Restriction: The format. must be of the same type as the source, either character or numeric.
Details
The format must be the same type (numeric or character) as the value of source. The result of the PUT
function is always a character string. If the source is numeric, the resulting string is right aligned. If the
source is character, the result is left aligned.
Use PUT to convert a numeric value to a character value. PUT writes (or produces a reformatted result)
only while it is executing. To preserve the result, assign it to a variable.
Comparisons
The PUT statement and the PUT function are similar. The PUT function returns a value using a specified
format. You must use an assignment statement to store the value in a variable. The PUT statement writes
a value to an external destination (either the SAS log or a destination you specify).
INPUT Returns the value produced when a SAS expression that uses a specified informat expression
is read
Syntax INPUT(source, <? | ??>informat.)
"#$%&'()*!
source contains the SAS character expression to which you want to apply a specific informat.
? or ??
The optional question mark (?) and double question mark (??) format modifiers suppress the
printing of both the error messages and the input lines when invalid data values are read. The ?
modifier suppresses the invalid data message. The ?? modifier also supresses the invalid data
message and, in addition, prevents the automatic variable _ERROR_ from being set to 1 when
invalid data are read.
informat.
is the SAS informat that you want to apply to the source.
Details
The INPUT function enables you to read the value of source by using a specified informat. The informat
determines whether the result is numeric or character. Use INPUT to convert character values to numeric
values.
118
Comparisons
The INPUT function returns the value produced when a SAS expression is read using a specified
informat. You must use an assignment statement to store that value in a variable. The INPUT statement
uses an informat to read a data value and then optionally stores that value in a variable.
Examples
+,-&./'!01!<D(@'#)4($!8%&'#49!:-/%'*!)D!<=-#-9)'#!:-/%'!!
In this example, the first statement converts the values of CC, a numeric variable, into the four-character
hexadecimal format, and the second writes the same value that the PUT function returns.
cchex=put(cc,hex4.);
put cc hex4.;
+,-&./'!61!<D(@'#)4($!<=-#-9)'#!:-/%'*!)D!8%&'#49!:-/%'*!!
This example uses the INPUT function to convert a character value to a numeric value and store it in
another variable. The COMMA9. informat reads the value of the SALE variable, stripping the commas.
The resulting value, 2115353, is stored in FMTSALE.
data testin;
input sale $9.;
fmtsale=input(sale,comma9.);
datalines;
2,115,353
;
+,-&./'!61!?*4($!E?Q!-(M!78E?Q!W%(9)4D(*!!
In this example, PUT returns a numeric value as a character string. The value 122591 is assigned to the
CHARDATE variable. INPUT returns the value of the character string as a SAS date value using a SAS
date informat. The value 11681 is stored in the SASDATE variable.
numdate=122591;
chardate=put(numdate,z6.);
sasdate=input(chardate,mmddyy6.);
119
L6. SAS Date, Time, and Datetime Values
Definitions
SAS date value
is a value that represents the number of days between January 1, 1960, and a specified date. SAS
can perform calculations on dates ranging from A.D. 1582 to A.D. 19,900. Dates before January
1, 1960, are negative numbers; dates after are positive numbers.
! SAS date values account for all leap year days, including the leap year day in the year 2000.
! SAS date values can reliably tell you what day of the week a particular day fell on as far back
as September 1752, when the calendar was adjusted by dropping several days. SAS day-of-
the-week and length-of-time calculations are accurate in the future to A.D. 19,900.
! Various SAS language elements handle SAS date values: functions, formats and informats.
SAS time value
is a value representing the number of seconds since midnight of the current day. SAS time values
are between 0 and 86400.
SAS datetime value
is a value representing the number of seconds between January 1, 1960 and an
hour/minute/second within a specified date.
The following figure shows some dates written in calendar form and as SAS date values.
How SAS Converts Calendar Dates to SAS Date Values
120
Working with SAS Dates and Times
7(3D#&-)*!-(M!WD#&-)*!
The SAS System converts date, time and datetime values back and forth between calendar dates and
clock times with SAS language elements called formats and informats.
! Formats present a value, recognized by SAS, such as a time or date value, as a calendar date or
clock time in a variety of lengths and notations.
! Informats read notations or a value, such as a clock time or a calendar date, which may be in a
variety of lengths, and then convert the data to a SAS date, time, or datetime value.
2-)'!-(M!Q4&'!QDD/*!L5!Q-*K!
The following table correlates tasks with various SAS System language elements that are available for
working with time and date data.
To write SAS date values in recognizable forms use this DATE FORMATS (PRINCIPALI)
121
To read calendar dates as SAS date use this DATE INFORMATS (PRINCIPALI) Note: YEARCUTOFF=1920
List Input Result MMDDYY10. 03172000 14686
DATEw. 17MAR2000 -14534 MONYYw. MAR00 14670
DATE9. 17MAR2000 14686 NENGOw. H.12/03/17 14686
DDMMYYw. 170300 14686 YYMMDDw. 000317 14686
DDMMYY8. 17032000 14686 YYMMDD10. 20000317 14686
MMDDYYw. 031700 14686 YYQw. 00Q1 14610
Examples
122
+,-&./'!01!24*./-54($!2-)'Y!Q4&'Y!-(M!2-)')4&'!:-/%'*!-*!G'9D$(4Z-L/'!2-)'*!-(M!Q4&'*!
The following example demonstrates how a value may be displayed as a date, a time, or a datetime.
Remember to select the SAS language element that converts a SAS date, time, or datetime value to the
intended date, time or datetime format. See the previous tables for examples.
Note:
! Time formats count the number of seconds within a day, so the values will be between 0 and
86400.
! DATETIME formats count the number of seconds since January 1, 1960, so for datetimes that are
greater than 02JAN1960:00:00:01, (integer of 86401) the datetime value will always be greater
than the time value.
! When in doubt, look at the contents of your data set for clues as to which type of value you are
dealing with.
This program uses the DATETIME, DATE and TIMEAMPM formats to display the value 86399 to a
date and time, a calendar date, and a time.
data test;
options nodate pageno=1 linesize=80 pagesize=60;
Time1=86399;
format Time1 datetime.;
Date1=86399;
format Date1 date.;
Time2=86399;
format Time2 timeampm.;
run;
proc print data=test;
title 'Same Number, Different SAS Values';
footnote1 'Time1 is a SAS DATETIME value';
footnote2 'Date1 is a SAS DATE value';
footnote3 'Time2 is a SAS TIME value'.;
run;
Datetime, Date and Time Values for 86399
Same Number, Different SAS Values 1
+,-&./'!61!G'-M4($Y![#4)4($Y!-(M!<-/9%/-)4($!2-)'!:-/%'*!
This program reads four regional meeting dates and calculates the dates on which announcements should
be mailed.
data meeting;
options nodate pageno=1 linesize=80 pagesize=60;
input region $ mtg : mmddyy8.;
sendmail=mtg-45;
datalines;
N 11-24-99
S 12-28-99
E 12-03-99
W 10-04-99
;
proc print data=meeting;
format mtg sendmail date9.;
title 'When To Send Announcements';
run;
Calculated Date Values: When to Send Mail
123
When To Send Announcements
Obs region mtg sendmail
1 N 24NOV1999 10OCT1999
2 S 28DEC1999 13NOV1999
3 E 03DEC1999 19OCT1999
4 W 04OCT1999 20AUG1999
data _null;
sdate='16oct78'd;
edate='16feb96'd; SAS Statements Results!
actual=datdif(sdate, edate, 'act/act');
days360=datdif(sdate, edate, '30/360'); put actual=; 6332
put actual= days360=;run; put days360=;! 6240
124
L7. ALCUNE FUNZIONI DI ARROTONDAMENTO
125
L8. ALCUNE FUNZIONI SULLE VARIABILI CARATTERE
SUBSTR (right of =) Extracts a substring from an argument
Syntax <variable=>SUBSTR(argument,position<,n>)
"#$%&'()*!
variable specifies a valid SAS variable name.
argument specifies any SAS character expression.
position specifies a numeric expression that is the beginning character position.
n specifies a numeric expression that is the length of the substring to extract.
Interaction: If n is larger than the length of the expression that remains in argument after position,
SAS extracts the remainder of the expression.
Tip: If you omit n, SAS extracts the remainder of the expression
The SUBSTR function returns a portion of SAS Statements Results
an expression that you specify in ----+----1----+----2
argument. The portion begins with the date='06MAY98';
character specified by position and is the month=substr(date,3,3);
year=substr(date,6,2);
number of characters specified by n. put @1 month @5 year; MAY 98
A variable that is created by SUBSTR
obtains its length from the length of
argument.
126
TRIM
Syntax TRIM(argument) Example 1: Removing Trailing Blanks
data test;
argument specifies any SAS character input part1 $ 1-10 part2 $ 11-20;
hasblank=part1||part2;
expression. noblank=trim(part1)||part2;
put hasblank;
Details put noblank;
TRIM copies a character argument, datalines;
removes all trailing blanks, and returns the Data Line Results
trimmed argument as a result. If the
argument is blank, TRIM returns one apple sauce ----+----1----+----2
blank. TRIM is useful for concatenating apple sauce
because concatenation does not remove
trailing blanks. applesauce
Assigning the results of TRIM to a
variable does not affect the length of the +,-&./'!61!<D(9-)'(-)4($!-!T/-(K!<=-#-9)'#!
receiving variable. If the trimmed value is
shorter than the length of the receiving +,.#'**4D(!!
variable, SAS pads the value with new
blanks as it assigns it to the variable. SAS Statements Results
Comparisons X="A"||trim(" ")||"B"; put x; A B
The TRIM and TRIMN functions are
similar. TRIM returns one blank for a x=" "; y=">"||trim(x)||"<"; put y; > <
blank string. TRIMN returns a null string
(zero blanks) for a blank string
UPCASE Converts all letters in an argument to uppercase
Syntax UPCASE(argument)
127
ALTRE PRINCIPALI FUNZIONI PER LE VARIABILI CARATTERE
128
M. APPROFONDIMENTI: LE MACRO SAS
2. I DSS così costruiti vanno concatenati uno di seguito all’altro con un passo di data del tipo:
data a.tutti;
set a.ANT1 a.ANT2 a.ANT3 a.ANT4 fino al DSS a.ANT80;
run;
In situazioni come questa la programmazione tramite macro permette di risolvere in modo rapido il
problema.
Una macro è una parte di programma SAS con un suo linguaggio e una sua sintassi particolare.
129
a.ant&i
%end;
%mend concatena;
Osserviamo che il parametro di macro i, quando viene utilizzato, è indicato con &i, cioè è
preceduto dal simbolo &, mentre quando viene dichiarato (nel ciclo do) è scritto senza
prefisso.
E’ possibile costruire una macro più generale che riceva dall’esterno, quando viene
chiamata, i due numeri di inizio e fine del nome dei DSS (nel caso precedente 1 e 80).
In tal caso il nome dei parametri di macro devono essere scritti tra parentesi dopo il nome:
%macro concatena(in, fin);
%do i=&in %to &fin;
a.ant&i
%end;
%mend concatena;
Abbiamo già visto che i parametri di macro (in questo caso in e fin) quando vengono
utilizzati devono essere preceduti dal simbolo &
La macro viene richiamata nel programma nel seguente modo:
data a.tutti;
set
%concatena(1,80) /* oppure %concatena(4,15) .... */
;
run;
Per costruire una stringa formata dalla concatenzione di due parametri di macro (&nomeds e &i),
bisogna che essi siano separati da . (punto)
&nomeds.&i
La macro viene richiamata nel programma nel seguente modo:
data a.tutti;
set %concatena(1,80,a.ant) ;
run;
Infine inseriamo nella macro anche la parte di programma relativa alla costruzione del DSS di
output, inserendo anche il nome di quest’ultimo fra i parametri di macro.
%macro concatena(nomeds,in,fin,dsout);
data &dsout;
set
%do i=&in %to &fin;
&nomeds.&i
%end;
;
run;
%mend concatena;
La sua chiamata è: %concatena(a.ant,4,8,a.finale);
130
Costruiamo ora una macro che semplifichi la lettura dei dati dai file di testo.
Inizialmente prendiamo in esemi i file numerati da 1 a 9.
%macro lettura;
%do n=1 %to 9;
data a.ant&n;
infile "C:\ANTARTIDE\m00&n..asc" firstobs=2;
input profond temper salinita x1 x2 x3 x4 fluoresc x5 x6 densita x7;
stazione=&n;
drop x1-x7;
run;
%end;
%mend lettura;
Osserviamo che:
1. dovendo scrivere un parametro di macro all’interno di una stringa delimitata dal
simbolo ' (apice) – vedi programma iniziale – bisogna rimpiazzare tale simbolo con il
simbolo " (virgolette o doppio apice)
2. i due punti che compaiono in
m00&n..asc
si riferiscono il primo alla separazione del parametro di macro dalla stringa successiva
e il secondo fa parte del nome del file
Anche in questo caso nella macro possono essere messi due parametri che indicano i numeri di
inizio e di fine dei nomi dei file di dati; può essere scritta anche una macro analoga per leggere i file da
m010 a m080 (cambia il numero di 0 nel nome)
%lettura(1,9); %lettura2(10,80)
Le due macro possono essere condensate in una sola utilizzando l’istruzione %if... %then...
%else...; del linguaggio delle macro.
%macro lettura(in,fin);
%do n=&in %to &fin;
data ant&n;
%if &n < 10 %then infile "C:\ANTARTIDE\m00&n..asc" firstobs=2;
%else infile "C:\ANTARTIDE\m0&n..asc" firstobs=2;
;
input profond temper salinita x1 x2 x3 x4 fluoresc x5 x6 densita x7;
stazione=&n;
drop x1-x7;
run;
%end;
%mend lettura;
Attenzione al ; dopo l’istruzione %if...%then...%else...;
La chiamata della macro è: %lettura(1,80);
131
M2. SAS Macro Language: Reference
The SAS macro language consists of statements, functions, and automatic macro variables.
Macro Statements
A macro language statement instructs the macro processor to perform an operation. It consists of a string
of keywords, SAS names, and special characters and operators, and it ends in a semicolon. Some macro
language statements are allowed only in macro definitions, but you can use others anywhere in a SAS
session or job, either inside or outside macro definitions (referred to as open code). Macro Language
Statements Allowed in Macro Definitions and Open Code lists macro language statements that you can
use in both macro definitions and open code.
Macro Language Statements Allowed in Macro Definitions and Open Code
Statement Description
%* comment designates comment text
%DISPLAY displays a macro window
%GLOBAL creates macro variables that are available during the execution of an entire SAS session
%INPUT supplies values to macro variables during macro execution
%KEYDEF assigns a definition to or identifes the definition of a function key
%LET creates a macro variable and assigns it a value
%MACRO begins a macro definition
%PUT writes text or the values of macro variables to the SAS log
%SYSCALL invokes a SAS call routine
%SYSEXEC issues operating system commands
%SYSLPUT defines a new macro variable or modifies the value of an existing macro variable on a
remote host or server
%SYSRPUT assigns the value of a macro variable on a remote host to a macro variable on the local host
%WINDOW defines customized windows
I)-)'&'()*!Q=-)!E'#3D#&!"%)D&-)49!+@-/%-)4D(!
Some macro statements perform an operation based on an evaluation of an arithmetic or logical
expression. They perform the evaluation by automatically calling the %EVAL function. If you get an
error message about a problem with %EVAL when a macro does not use %EVAL explicitly, check for
one of these statements. The macro statements that perform automatic evaluation are:
Character Functions
Character functions change character strings or provide information about them.
Macro Character Functions
Function Description
%INDEX returns the position of the first character of a string.
%LENGTH returns the length of a string
%SCAN, %QSCAN search for a word that is specified by a number. %QSCAN masks special
characters and mnemonic operataors in its result.
%SUBSTR, produce a substring of a character string. %QSUBSTR masks special characters
%QSUBSTR and mnemonic operators in its result.
%UPCASE, convert characters to uppercase. %QUPCASE masks special charactaers and
%QUPCASE mnemonic operators in its result.
For macro character functions that have a Q form (for example, %SCAN and %QSCAN), the two
functions work alike except that the function beginning with Q masks special characters and mnemonic
133
operators in its result. In general, use the function beginning with Q when an argument has been
previously masked with a macro quoting function or when you want the result to be masked (for example,
when the result may contain an unmatched quotation mark or parenthesis).
Many macro character functions have names corresponding to SAS character functions and perform
similar tasks (such as %SUBSTR and SUBSTR). But, macro functions operate before the DATA step
executes. Consider this DATA step:
data out.%substr(&sysday,1,3); /* macro function */
set in.weekly (keep=name code sales);
length location $4;
location=substr(code,1,4); /* SAS function */
run;
Running the program on Monday creates the data set name OUT.MON, as shown:
data out.MON; /* macro function */
set in.weekly (keep=name code sales);
length location $4;
location=substr(code,1,4); /* SAS function */
run;
Suppose that the IN.WEEKLY variable CODE contains the values cary18593 and apex19624. The SAS
function SUBSTR operates during DATA step execution and assigns these values to the variable
LOCATION, cary and apex.
Evaluation Functions
Evaluation functions evaluate arithmetic and logical expressions. They temporarily convert the operands
in the argument to numeric values. Then, they perform the operation specified by the operand and convert
the result to a character value. The macro processor uses evaluation functions to:
! make character comparisons
! evaluate logical (Boolean) expressions
! assign numeric properties to a token, such as an integer in the argument of a function.
\\\\OO!!
134
Other Functions
Three other macro functions do not fit into the earlier categories, but they provide important information.
Macro Quoting Functions lists these functions:
Macro Quoting Functions
Function Description
%SYSFUNC, execute SAS language functions or user-written functions within the macro
%QSYSFUNC facility.
%SYSGET returns the value of the specified host environment variable. For details, see the
SAS Companion for your operating system.
%SYSPROD reports whether a SAS software product is licensed at the site.
…………….
Macro Variables: Introduction
Macro variables are tools that enable you to dynamically modify the text in a SAS program through
symbolic substitution. You can assign large or small amounts of text to macro variables, and after that,
you can use that text by simply referencing the variable that contains it.
Macro variable values have a maximum length of 32K characters. The length of a macro variable is
determined by the text assigned to it instead of an explicit length declaration. So its length varies with
each value it contains. Macro variables contain only character data. However, the macro facility has
features that allow a variable to be evaluated as a number when it contains a value that can be interpreted
as a number. The value of a macro variable remains constant until it is explicitly changed. Macro
variables are independent of SAS data set variables.
Macro variables defined by macro programmers are called user-defined macro variables. Those defined
by the SAS System are called automatic macro variables. You can define and use macro variables
anywhere in SAS programs, except within data lines.
When a macro variable is defined, the macro processor adds it to one of the program's macro variable
symbol tables. When a macro variable is defined in a statement that is outside a macro definition (called
open code) or when the variable is created automatically by the SAS System (except SYSPBUFF), the
variable is held in the global symbol table, which SAS creates at the beginning of a SAS session. When a
macro variable is defined within a macro and is not explicitly defined as global, the variable is typically
held in the macro's local symbol table, which SAS creates when the macro starts executing.
When it is in the global symbol table, a macro variable exists for the remainder of the current SAS
session. A variable in the global symbol table is called a global macro variable. It has global scope
because its value is available to any part of the SAS session.
When it is in a local symbol table, a macro variable exists only during execution of the macro in which it
is defined. A variable in a local symbol table is called a local macro variable. It has local scope because
its value is available only until the macro stops executing. Chapter 2 contains figures that illustrate a
program with a global and a local symbol table.
Using Macro Variables
After a macro variable is created, you typically use the variable by referencing it with an ampersand
preceding its name (&variable-name), which is called a macro variable reference. These references
perform symbolic substitutions when they resolve to their value. You can use these references anywhere
in a SAS program. To resolve a macro variable reference that occurs within a literal string, enclose the
string in double quotation marks. Macro variable references that are enclosed in single quotation marks
are not resolved. Compare the following statements that assign a value to macro variable DSN and use it
in a TITLE statement:
%let dsn=Newdata;
135
title1 "Contents of Data Set &dsn";
title2 'Contents of Data Set &dsn';
In the first TITLE statement, the macro processor resolves the reference by replacing &DSN with the
value of macro variable DSN. In the second TITLE statement, the value for DSN does not replace
&DSN. The SAS System sees the following statements:
TITLE1 "Contents of Data Set Newdata";
TITLE2 'Contents of Data Set &dsn';
You can refer to a macro variable as many times as you need to in a SAS program. The value remains
constant until you change it. For example, this program refers to macro variable DSN twice:
%let dsn=Newdata;
data temp;
set &dsn;
if age>=20;
run;
proc print;
title "Subset of Data Set &dsn";
run;
Each time the reference &DSN appears, the macro processor replaces it with Newdata. Thus, the SAS
System sees these statements:
DATA TEMP;
SET NEWDATA;
IF AGE>=20;
RUN;
PROC PRINT;
TITLE "Subset of Data Set NewData";
RUN;
Note: If you reference a macro variable that does not exist, a warning message is printed in the SAS log.
For example, if macro variable JERRY is misspelled as JERY, the following produces an unexpected
result:
%let jerry=student;
data temp;
x="produced by &jery";
run;
This produces the following message:
WARNING: Apparent symbolic reference JERY not resolved.
136
Notice that macro variable references do not require the concatenation operator as the DATA step does.
The SAS System forms the resulting words automatically.
2'/4&4)4($!H-9#D!:-#4-L/'!8-&'*!U4)=4(!Q',)!
Sometimes when you use a macro variable reference as a prefix, the reference does not resolve as you
expect if you simply concatenate it. Instead, you may need to delimit the reference by adding a period to
the end of it.
A period immediately following a macro variable reference acts as a delimiter; that is, a period at the end
of a reference forces the macro processor to recognize the end of the reference. The period does not
appear in the resulting text.
Continuing with the example above, suppose that you need another DATA step that uses the names
SALES1, SALES2, and INSALES.TEMP. You might add the following step to the program:
/* first attempt to add suffixes--incorrect */
data &name1 &name2;
set in&name.temp;
run;
After macro variable resolution, the SAS System sees these statements:
DATA &NAME1 &NAME2;
SET INSALESTEMP;
RUN;
None of the macro variable references have resolved as you intended. The macro processor issues
warning messages, and the SAS System issues syntax error messages. Why?
Because NAME1 and NAME2 are valid SAS names, the macro processor searches for those macro
variables rather than for NAME, and the references pass into the DATA statement without resolution.
In a macro variable reference, the word scanner recognizes that a macro variable name has ended when it
encounters a character that is not allowed in a SAS name. However, you can use a period ( . ) as a
delimiter for a macro variable reference. For example, to cause the macro processor to recognize the end
of the word NAME in this example, use a period as a delimiter between &NAME and the suffix:
/* correct version */
data &name.1 &name.2;
The SAS System now sees this statement:
DATA SALES1 SALES2;
<#'-)4($!-!E'#4DM!)D!WD//DU!G'*D/@'M!Q',)!
Sometimes you need a period to follow the text resolved by the macro processor. For example, a two-
level data set name needs to include a period between the libref and data set name.
When the character following a macro variable reference is a period, use two periods. The first is the
delimiter for the macro reference, and the second is part of the text. For example,
set in&name..temp;
After macro variable resolution, the SAS System sees this statement:
SET INSALES.TEMP;
You can end any macro variable reference with a delimiter, but the delimiter is necessary only if the
characters that follow can be part of a SAS name. For example, both of these TITLE statements are
correct:
title "&name.--a report";
title "&name--a report";
They produce:
TITLE "sales--a report";
137
Forcing a Macro Variable to Be Local
At times you need to ensure that the macro processor creates a local macro variable rather than changing
the value of an existing macro variable. In this case, use the %LOCAL statement to create the macro
variable.
Explicitly make all macro variables created within macros local when you do not need their values after
the macro stops executing. Debugging the large macro programs is easier if you minimize the possibility
of inadvertently changing a macro variable's value. Also, local macro variables do not exist after their
defining macro finishes executing, while global variables exist for the duration of the SAS session;
therefore, local variables use less overall storage.
Suppose you want to use the macro NAMELST to create a list of names for a VAR statement, as shown
here:
%macro namelst(name,number);
%do n=1 %to &number;
&name&n
%end;
%mend namelst;
You invoke NAMELST in this program:
%let n=North State Industries;
proc print;
var %namelst(dept,5);
title "Quarterly Report for &n";
run;
After macro execution, the SAS compiler sees the following statements:
proc print;
var dept1 dept2 dept3 dept4 dept5;
title "Quarterly Report for 6";
run;
The macro processor changes the value of the global variable N each time it executes the iterative %DO
loop. (After the loop stops executing, the value of N is 6, as described in " %DO" in Chapter 13, "Macro
Language Dictionary.") To prevent conflicts, use a %LOCAL statement to create a local variable N, as
shown here:
%macro namels2(name,number);
%local n;
%do n=1 %to &number;
&name&n
%end;
%mend namels2;
Now execute the same program:
%let n=North State Industries;
proc print;
var %namels2(dept,5);
title "Quarterly Report for &n";
run;
The macro processor generates the following statements:
proc print;
var dept1 dept2 dept3 dept4 dept5;
title "Quarterly Report for North State Industries";
run;
Global and Local Variables with the Same Name shows the symbol tables before NAMELS2 executes,
while NAMELS2 is executing, and when the macro processor encounters the reference &N in the TITLE
statement.
138
Creating Global Macro Variables
The %GLOBAL statement creates a global macro variable if a variable with the same name does not
already exist there, regardless of what scope is current.
For example, in the macro NAME4, the macro CONDITN contains a %GLOBAL statement that creates
the macro variable COND as a global variable:
%macro conditn;
%global cond;
%let old=sales;
%let cond=cases>0;
%mend conditn;
Here is the rest of the program:
%let new=inventry;
%macro name4;
%let new=report;
%let old=warehse;
%conditn
data &new;
set &old;
if &cond;
run;
%mend name4;
%name4
Invoking NAME4 generates these statements:
data report;
set sales;
if cases>0;
run;
Suppose you want to put the SAS DATA step statements outside NAME4. In this case, all the macro
variables must be global for the macro processor to resolve the references. You cannot add OLD to the
%GLOBAL statement in CONDITN because the %LET statement in NAME4 has already created OLD
as a local variable to NAME4 by the time CONDITN begins to execute. (You cannot use the %GLOBAL
statement to make an existing local variable global.)
Thus, to make OLD global, use the %GLOBAL statement before the variable reference appears anywhere
else, as shown here in the macro NAME5:
%let new=inventry;
%macro conditn;
%global cond;
%let old=sales;
%let cond=cases>0;
%mend conditn;
%macro name5;
%global old;
%let new=report;
%let old=warehse;
%conditn
%mend name5;
%name5
data &new;
set &old;
if &cond;
run;
Now the %LET statement in NAME5 changes the value of the existing global variable OLD rather than
creating OLD as a local variable. The SAS compiler sees the following statements:
data report;
set sales;
if cases>0;
run;
139
N. COME OPERARE SU MATRICI IN SAS
N1. IL MODULO SAS/IML
Il calcolo matriciale in SAS può essere effettuato tramite una procedura a cui si accede con il
comando:
proc iml;
e da cui si esce con il comando:
quit;
Le istruzioni possono essere eseguite in modo interattivo o essere inserite in programmi.
La procedura è provvista di un linguaggio di programmazione che prevede il trattamento di
espressioni aritmetiche e carattere, input e output di dati, controlli sull'esecuzione (if, do, goto,...).
Gli elementi di dati fondamentali sono le matrici.
Le espressioni usano operatori che si applicano alle intere matrici.
La procedura incorpora un vocabolario molto ampio di operatori, funzioni e routine.
Non è necessario dichiarare dimensioni, spazi, attributi, ...
Ha un solo difetto! Non è immediato il passaggio dalle strutture di dati proprie del linguaggio
SAS (Data Set SAS) alle corrispondenti strutture matriciali e viceversa.
L'uso dell'operando VAR e di WHERE è analogo al precedente (le variabili devono essere tutte
numeriche o tutte carattere; numeriche è il default).
Il range serve per specificare ulteriormente le osservazioni da considerare.
<range> =
ALL tutte le osservazioni
CURRENT l'oss. corrente (default)
NEXT l'oss. successiva alla corrente
AFTER tutte le successive alla corrente
<operando POINT>
Esempi di operando POINT:
POINT 10 l'osservazione 10
POINT {10 25} le oss. 10 e 25
POINT (20 : 25) le oss. dalla 20 alla 25
POINT ((20 : 25) | | (30 : 35)) le oss. dalla 20 alla 25 e dalla 30 alla 35
Esempi:
READ ALL VAR {X Y} INTO MAT;tutte le osservazioni delle variabili X e Y
READ POINT 23 INTO MAT; tutte le variabili numeriche dell'osservazione 23
Esempio:
Per costruire un Data Set SAS di nome PLUTO da una matrice di nome A con variabili uguali alle
colonne di A e con osservazioni le righe di A si usano le istruzioni:
CREATE pluto FROM a;
APPEND FROM a;
L'istruzione CREATE crea il Data Set; in questa forma semplice le variabili hanno nome COL1,
COL2, COLn.
L'istruzione APPEND aggiunge dati alla fine del Data Set.
OPERAZIONI ARITMETICHE
Operazioni matriciali
M = A * B prodotto righe per colonne
M = A ** s equivale a M = A +#A +#,,,#+#A (s volte) (A deve essere quadrata)
M = A ** (-1) equivale a M = INV(A) matrice inversa
M = A @ B prodotto di Kronecker o prodotto diretto
se: A mat. n x m, B mat. h x k allora M mat. nh x mk
s = TRACE(A) somma gli elementi diagonali
M = A < B M = A > B M = A = B
M = A <= B M = A >= B M = A ^= B
M è una matrice di 0 e 1
FUNZIONI DI INDAGINE
Permettono di controllare se tutti o alcuni elementi di una matrice sono diversi da 0, per trovare il
numero di elementi uguali a 0, il numero di righe e colonne, ...
FUNZIONI DI RIDUZIONE
Permettono di calcolare il massimo, il minimo, la somma e la somma dei quadrati degli elementi di
una matrice.
142
FUNZIONI E CALL DI ALGEBRA LINEARE
s = DET(M) determinante
M = INV (A) inversa
CALL EIGEN (v,M,A) crea un vettore v con gli autovalori (in ordine decrescente), una
matrice M con colonne i corrispondenti autovettori di una matrice
quadrata A
v = EIGVAL (A) crea una vettore v con gli autovalori di A
M = EIGVEC (A) crea una matrice M con colonne gli autovettori di A
CALL SVD (U,q,V,A) decompone la matrice A, di dimensioni m x n, con n"m:
A = U + diag (q) + V'
dove: U'U = V'V = VV' = In
U, matrice m x n, autovettori normalizzati di AA'
q, vettore n, valori singolari (rad. quadr. AA' e A'A)
V, matrice n x n, autovettori di A'A
U = ROOT (A) A deve essere simmetrica, definita non negativa
crea una matrice triangolare superiore, U'U=A
x = SOLVE (A,B) A quadrata e non singolare
risolve l'insieme di equazioni lineari A x = B
non usare x=INV(A+B)
143