• Non ci sono risultati.

NOTE INTRODUTTIVE AL SISTEMA SAS

N/A
N/A
Protected

Academic year: 2021

Condividi "NOTE INTRODUTTIVE AL SISTEMA SAS"

Copied!
144
0
0

Testo completo

(1)

DIPARTIMENTO DI MATEMATICA UNIVERSITÀ DI GENOVA Via Dodecaneso, 35 - 16146 GENOVA (Italy)

tel. +39-010-3536751 fax +39-010-3536752

NOTE INTRODUTTIVE AL SISTEMA SAS

Fabio Rapallo - Ivano Repetto - Maria Piera Rogantin

Dipartimento di Matematica - Università di Genova

(2)
(3)

INDICE

A. Aspetti generali A1. Il linguaggio SAS A2. I passi di DATA A3. I passi di PROC

A4. I DATA SET di tipo SAS A5. Tipi di variabili

B. Come eseguire un programma SAS C. Esempi di programmi SAS

C1. Primo esempio

C2. Secondo esempio: le procedure PRINT e CONTENTS C3. Osservazioni per la scrittura dei programmi

D. Il passo di DATA

D1. Creazione di un DATA SET SAS D2. Alcuni esempi

D3. DATA SET SAS permanenti E. Manipolazione dei DATA SET

E1. Selezione di sottoclassi di osservazioni E2. Selezione di osservazioni consecutive E3. Selezione di variabili

E4. Cambio di nome a variabili

E5. Costruzione di più DATA SET SAS E6. Concatenazione di più DATA SET SAS E7. Lettura di DATA SET di "tipo" diverso F. Ancora sul passo di DATA

F1. Espressioni e funzioni SAS F2. I valori mancanti

F3. Somme cumulate

F4. Approfondimenti sull’esecuzione di un passo di DATA F5. Gli array

F6. Istruzioni di controllo F7. L'istruzione INPUT F8. L'istruzione INFILE F9. L'istruzione OUTPUT

F10. Scrittura su un file esterno e istruzione PUT G. Il passo di PROC

G1. Alcune opzioni e istruzioni usato in un passo di PROC G2. Procedura SORT

G3. Procedura PRINT G4. Procedura MEANS

G5. Procedura FREQ (e procedura FORMAT) G6. Procedura UNIVARIATE

G7. Altre procedure statistiche elementari

G8. Alcune procedure che operano su DATA SET SAS G9. Selezione di variabili e di osservazioni in una procedura H. Istruzioni e procedure grafiche

H1. Alcune istruzioni per gli output grafici H2. Procedura GCHART

H3. Procedura GPLOT I. Errori e lettura del LOG

(4)

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

(5)

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.

Il SAS consente di:

- leggere dati

- trasformare e manipolare di dati (mediante l'utilizzo di funzioni matematiche e statistiche, di concatenazione e di ordinamento)

- aggiornare dati - stampare prospetti - generare grafici

- ridurre e sintetizzare dati

- effettuare analisi matematiche sui dati

Ogni programma è composto da passi (STEP).

Esistono 2 tipi di passi: i passi di DATA e i passi di PROC.

A2. I PASSI DI DATA

Si usano per creare DATA SET SAS partendo da files già esistenti. Tali files possono essere non SAS (grezzi), o già di tipo SAS. I dati in ingresso possono subire trattamenti durante il passo di DATA.

dati grezzi DATA SET SAS

dati grezzi DATA SET SAS passo di DATA

Un passo di data inizia con l'istruzione DATA seguito dal nome del Data Set Sas che si vuole costruire.

A3. I PASSI DI PROC

Servono per produrre tabulati, rapporti, statistiche, ecc.

I dati su cui operano devono già essere in formato DATA SET SAS.

Con un passo di Proc si possono creare anche altri DATA SET SAS che possono essere analizzati successivamente da altri passi di DATA o di PROC.

Un passo di proc inizia con l'istruzione PROC seguito dal nome della procedura che si vuole eseguire.

Un passo di programma (di data o di proc) termina con l'istruzione

RUN;

o con un nuovo passo di data o di proc.

(6)

A4. I DATA SET DI TIPO SAS

Un DATASET di tipo SAS è un insieme di dati omogenei organizzati in forma rettangolare.

ESEMPIO:

variabili

osservazioni

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;

Un DATA SET SAS si compone di due parti distinte:

- una parte descrittiva in cui vengono memorizzate tutte le informazioni necessarie affinchè il SAS possa in un qualunque momento rileggere i dati in modo totalmente automatico (es.: nomi e attributi delle variabili, "storia" di come è stato costruito, ... );

- una parte in cui vengono memorizzati i dati propriamente detti.

Per visualizzare le due parti, si devono usare delle PROC diverse.

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.

A5. TIPI DI VARIABILI

Una variabile può essere di due tipi:

- NUMERICA (es. età, altezza, peso) - CARATTERE (es. cognome, sesso)

Una variabile è caratterizzata da una serie di attributi:

- nome

- lunghezza (LENGTH)

- formato di ingresso (INFORMAT) - formato di uscita (FORMAT) - etichetta (LABEL)

che possono essere specificati con opportune istruzioni.

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).

Il SAS esegue automaticamente una conversione da variabile numerica a carattere quando:

- una variabile numerica è assegnata ad una variabile carattere definita precedentemente;

- una funzione agisce su una variabile numerica ma ha un formato carattere come argomento;

- una variabile numerica è usata come operando di un operatore tipico delle variabili carattere (esempio l'operatore di concatenazione di stringhe).

(7)

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

(8)

C. ESEMPI DI PROGRAMMA SAS

C1 PRIMO ESEMPIO

Con questo programma:

- si costruisce un data set SAS di nome CLASSE leggendo i dati inseriti nel programma - si ordinano i dati secondo una variabile

- si stampa il contenuto del DSS costruito - si costruiscono alcune statistiche

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; - lavora sull'ultimo Data Set

BY ES_DATI; run; - ordina le oss. rispetto alla variabile ES_DATI

PROC PRINT; - 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; - stampa le informazioni sul Data Set con il titolo assegnato precedentemente

PROC MEANS; - calcola alcune statistiche su tutte le variabili numeriche con il titolo precedente

RUN; - determina l'esecuzione del passo di proc

PROC MEANS; - calcola alcune statistiche sulle variabili indicate

var a_nascit; dopo l’istruzioneVAR

RUN; - determina l'esecuzione del passo di proc

OUTPUT SAS della procedura PRINT:

STUDENTI ORDINATI PER NUMERO ESAMI DATI

OBS NOME A_CORSO A_NASCITA ES_DATI MEDIA

1 TTT 3 1967 9 100

2 XXX 1F 1965 12 95

3 WWW 4 1968 12 107

4 ZZZ 4R 1966 13 100

(9)

C2 SECONDO ESEMPIO: LE PROCEDURE PRINT E CONTENTS

Con questo programma:

- si costruisce un data set SAS di nome ES1 leggendo i dati inseriti nel programma - si costruiscono nuove variabili da quelle di partenza

- si stampa il contenuto del DSS costruito (sia i dati che la descrizione)

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;

title ' ';run; i due primi run non sono necessari

proc contents;run;

(10)

OUTPUT SAS:

L'output della proc print è il seguente:

OBS SESSO ETA HINCH WLIB ALTEZZA PESO 1 f 14 56.3 85.0 143.002 38.5560 2 f 15 62.3 105.0 158.242 47.6280 3 f 15 63.3 108.0 160.782 48.9888 4 f 16 59.0 92.0 149.860 41.7312 5 f 19 62.5 112.5 158.750 51.0300 6 f 17 62.5 112.0 158.750 50.8032 7 f 18 59.0 104.0 149.860 47.1744 8 f 14 56.5 69.0 143.510 31.2984 9 f 16 62.0 94.5 157.480 42.8652

(non è riportato una parte dell'output)

230 m 15 57.3 80.5 145.542 36.5148 231 m 17 63.5 102.5 161.290 46.4940 232 m 14 55.0 76.0 139.700 34.4736 233 m 16 66.5 112.0 168.910 50.8032 234 m 18 65.0 114.0 165.100 51.7104 235 m 16 61.5 140.0 156.210 63.5040 236 m 16 62.0 107.5 157.480 48.7620

L'output della proc contents è il seguente:

CONTENTS PROCEDURE

Data Set Name: WORK.ES1 Observations: 236 Member Type: DATA Variables: 6 Engine: V611 Indexes: 0 Created: 10:55 Friday, December 4, 1998 Observation Length: 48 Last Modified: 10:55 Friday, December 4, 1998 Deleted Observations: 0 Protection: Compressed: NO Data Set Type: Sorted: NO Label:

---Engine/Host Dependent Information--- Data Set Page Size: 8192

Number of Data Set Pages: 2 File Format: 607 First Data Page: 1 Max Obs per Page: 169 Obs in First Data Page: 147

---Alphabetic List of Variables and Attributes--- # Variable Type Len Pos

--- 5 ALTEZZA Num 8 32 2 ETA Num 8 8 3 HINCH Num 8 16 6 PESO Num 8 40 1 SESSO Char 8 0 4 WLIB Num 8 24

(11)

C3. OSSERVAZIONI PER LA SCRITTURA DEI PROGRAMMI

- le istruzioni terminano con il carattere " ; "

- si possono usare tutte le colonne di una linea

- si possono scrivere più istruzioni su una linea (separate ovviamente da ;) - si può scrivere una istruzione su più linee

- si possono mettere più istruzioni "RUN" all'interno di un programma

- i commenti vanno compresi fra /* e */ ( es. PROC SORT; /* ordinamento dei dati */ ) ABBREVIAZIONI PER LISTE DI VARIABILI

a) X1-Xn si considerano tutte le variabili da X1 a Xn ( X1 X2 X3 ... Xn) b) X--A si considerano tutte le variabili da X a A

X-NUMERIC-A si considerano tutte le variabili numeriche da X a A X-CHARACTER-A si considerano tutte le variabili carattere da X a A c) _NUMERIC_ si considerano tutte le variabili numeriche

_CHARACTER_ si considerano tutte le variabili carattere _ALL_ si considerano tutte le variabili

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;

OUTPUT SAS:

Obs x1 x2 y x3 1 1 2 3 4 2 6 7 8 9

proc print; var x1-x3; run;

OUTPUT SAS:

Obs x1 x2 x3 1 1 2 4 2 6 7 9 proc print; var x1--x5; run;

OUTPUT SAS:

Obs x1 x2 y x3 x5 1 1 2 3 4 5 2 6 7 8 9 0

proc print; var x1-x5; run;

LOG SAS:

ERROR: Variable X4 in suffix list not in data set.

(12)

D. IL PASSO DI DATA

D1. CREAZIONE DI UN DATA SET SAS

DATI SU FILE ESTERNO:

DATA nome Data Set ;

INFILE '[path] nome ' ; apre il file per la lettura

INPUT ...; descrive l'input assegnando un nome alle variabili con eventuale formato di lettura.

altre istruzioni usate nel passo di DATA ;

DATI INSERITI NEL PROGRAMMA:

DATA nome Data Set ;

INPUT ...;

altre istruzioni ;

DATALINES; immediatamente prima dei dati

linee di dati

; indica la fine dei dati

DATI DA UN ALTRO DATA SET:

DATA nome del nuovo Data Set ;

SET nome del Data Set da cui leggere i dati;

altre istruzioni ;

OSS: oltre all'istruzione SET si possono usare anche le istruzioni MERGE e PUT con risultato analogo.

(13)

D2. ALCUNI ESEMPI

DATI INSERITI NEL PROGRAMMA:

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;

DATI SU FILE ESTERNO:

PROGRAMMA SAS n. 3:

data es2;

infile 'a:es1.txt';

input sesso $ eta hinch wlib;

altezza=hinch*2.54;

peso=wlib*0.4536;

run;

DATI DA UN ALTRO DATA SET:

PROGRAMMA SAS n. 4:

data es3;

set es2;

if eta < 16 then cl_eta = 'giovane';

else cl_eta='vecchio';

run;

proc print;

var eta cl_eta;

run;

(14)

D3. DATA SET SAS PERMANENTI

COME RENDERE PERMANENTE UN DATA SET SAS a) bisogna creare una "libreria" con l'istruzione:

LIBNAME nome simbolico libreria ' path '; si indica la directory dove scrivere i

Data Set permanenti

b) quando si costruisce il Data Set bisogna scrivere:

DATA nome simbolico libreria .nome Data Set ; l'estensione del file costruito è SD2 INPUT ...;

...

I Data Set sono conservati con il nome: nome Data Set .SD2 nel path specificato dall'istruzione LIBNAME.

Esempio.

PROGRAMMA SAS n. 5:

libname corso 'a:\corsosas';

data corso.es3;

set es2;

if eta < 16 then cl_eta = 'giovane';

else cl_eta='vecchio';

run;

proc print;

var eta cl_eta;

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.

COME ACCEDERE AD UN DATA SET PERMANENTE DATA nome nuovo Data Set ;

SET nome simbolico libreria .nome Data Set ; ...

data corso.nuovo;

set corso.es3;

(15)

E. MANIPOLAZIONE DI DATA SET

Consideriamo il seguente esempio.

PROGRAMMA SAS n. 6:

libname corso 'a:\corsosas';

data corso.disney;

length nome $ 12;

input nome $ & sesso $ eta altezza peso;

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; 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 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

E1. SELEZIONE DI SOTTOCLASSI DI OSSERVAZIONI

La selezione di sottoclassi di osservazioni contenute in un Data Set può avvenire con diverse forme.

Presentiamo alcune di queste possibilità continuando l'esempio precedente:

PROGRAMMA SAS n. 7:

data maschi; il DDS costruito è temporaneo

set corso.disney; nome DSS con i dati di cui si vuole selezionare una sottoclasse

if sesso='m'; precisa il criterio di selezione

proc print; run;

l'istruzione: if sesso='m';

può essere sostituita equivalentemente dalle istruzioni if sesso ^='m' then delete;

if sesso ='m' then output;

(16)

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

E2. SELEZIONE DI OSSERVAZIONI CONSECUTIVE

Si possono usare varie opzioni dell'istruzione SET, di cui presentiamo alcune possibilità (riferite sempre all'esempio di partenza):

PROGRAMMA SAS n. 8:

data prime3;

set corso.disney(obs=3);

proc print;

data dalla3;

set corso.disney(firstobs=3);

proc print;

data centrali;

set corso.disney(firstobs=3 obs=5);

proc print;

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

OBS NOME SESSO ETA ALTEZZA PESO 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

OBS NOME SESSO ETA ALTEZZA PESO 1 minnie f 35 145 40 2 clarabella f 30 180 65 3 nonna papera f 99 140 55

(17)

PROGRAMMA SAS n. 8 bis

data es2bis;

infile 'a:es1.txt' firstobs=3;

input sesso $ eta hinch wlib;

proc print;

OUTPUT SAS:

OBS SESSO ETA HINCH WLIB 1 f 153 63.3 108.0 2 f 161 59.0 92.0 3 f 191 62.5 112.5 4 f 171 62.5 112.0 5 f 185 59.0 104.0 6 f 142 56.5 69.0 7 f 160 62.0 94.5 8 f 140 53.8 68.5 9 f 139 61.5 104.0 10 f 178 61.5 103.5 11 m 153 57.8 79.5 12 m 155 57.3 80.5 13 m 178 63.5 102.5 14 m 142 55.0 76.0 15 m 164 66.5 112.0

(è omessa una parte dell’output)

E3. SELEZIONE DI VARIABILI

La selezione delle variabili avviene mediante l'utilizzo delle istruzioni DROP e KEEP.

Queste istruzioni sono complementari e servono per specificare:

- quali variabili del vEcchio Data Set non si vogliono ricopiare nel nuovo (istruzione DROP).

- quali variabili del vecchio Data Set si vogliono ricopiare nel nuovo (istruzione KEEP).

Le istruzioni DROP e KEEP sono non eseguibili. Possono pertanto comparire in qualunque punto di un passo di Data.

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:

PROGRAMMA SAS n. 10:

data etasesso;

set corso.disney(drop = altezza peso);

...

run;

(18)

In tal caso le variabili ALTEZZA e PESO non possono essere usate in alcun modo nel nuovo Data Set.

E4. CAMBIO DI NOME A VARIABILI

È sufficiente usare l'istruzione RENAME come segue:

PROGRAMMA SAS n. 10:

data nuovo(rename=(sesso=mf));

set corso.disney;

/* altre istruzioni */

run;

E5. COSTRUZIONE DI PIÙ DATA SET

Si usano le istruzioni IF e SELECT che permettono di effetuare delle scelte condizionate.

Esempio.

PROGRAMMA SAS n. 11:

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_;

proc print data=corso.maschi;

proc print data=corso.femmine;

run;

oppure:

data corso.maschi corso.femmine;

set corso.disney;

select(sesso);

when('m') output corso.maschi;

when('f') output corso.femmine;

otherwise put 'osservazioni sbagliate' _all_;

end;

proc print data=corso.maschi;

proc print data=corso.femmine;

run;

OUTPUT SAS: (in entrambi i casi)

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

OBS NOME SESSO ETA ALTEZZA PESO 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

(19)

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.

PROGRAMMA SAS n. 11 bis:

data errore;

if nome='paperino' then sesso='M';

data corso.maschi corso.femmine;

set errore;

if sesso='m' then output corso.maschi;

else if sesso='f' then output corso.femmine;

else put 'osservazioni sbagliate ' _all_;

run;

LOG SAS:

osservazioni sbagliate nome= sesso= _ERROR_=0 _N_=2

E6. CONCATENAZIONE DI PIÙ DATA SET

Si usa ancora una volta l'istruzione SET, come nel seguente esempio in cui i DS hanno le stesse variabili:

PROGRAMMA SAS n. 12:

data corso.tutti;

set corso.maschi corso.femmine;

proc print ; run;

OUTPUT SAS della proc print:

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 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

L'istruzione Set usata nel seguente modo produrrebbe un output diverso:

PROGRAMMA SAS n. 13:

data corso.tutti2;

set corso.maschi;

set corso.femmine;

proc print ; run;

OUTPUT SAS n. 14:

OBS NOME SESSO ETA ALTEZZA PESO 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

(20)

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".

PROGRAMMA SAS n. 14:

data corso.maschi1;

set corso.maschi;

keep nome sesso eta;

data corso.maschi2;

set corso.maschi;

keep nome altezza peso;

data corso.maschi3;

set corso.maschi1;

set corso.maschi2;

proc print; run;

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:

PROGRAMMA SAS n. 15:

proc sort data=corso.maschi1 out=corso.maschi1s;

by nome;

proc sort data=corso.maschi2 out=corso.maschi2s;

by nome;

data corso.maschi3s;

merge corso.maschi1s corso.maschi2s;

by nome;

proc print; 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:

(21)

data uno;

input n $ x y;

datalines;

a 12 13 b 14 15 d 16 17

;

data due;

input n $ x z;

datalines;

a 22 23 b 24 25 c 26 27

;

data tre;

set uno;

set due;

proc print; run;

OUTPUT SAS:

Obs n x y z 1 a 22 13 23 2 b 24 15 25

3 c 26 17 27 ATTENZIONE A QUESTA OSSERVAZIONE data quattro;

merge uno due;

by n;

proc print; run;

OUTPUT SAS:

Obs n x y z 1 a 22 13 23 2 b 24 15 25 3 c 26 . 27 4 d 16 17 .

E7. LETTURA DI DATI DA DATA SET DI "TIPO" DIVERSO

Consideriamo il seguente esempio:

PROGRAMMA SAS n. 16:

proc means data=corso.disney; legge dal Data Set corso.disney

var altezza peso; opera solo sulle variabili altezza e peso output out=sommario mean=m_alt m_peso; dà alle due medie i nomi e costruisce il Data Set

proc print data=sommario;

run;

OUTPUT SAS della proc print:

OBS _TYPE_ _FREQ_ M_ALT M_PESO 1 0 11 137.818 39

Se si vuole costruire un Data Set con gli scarti dalle medie bisogna operare nel seguente modo.

PROGRAMMA SAS n. 17:

data corso.diney1;

if _n_=1 then set sommario;

set corso.disney;

alt_c=altezza-m_alt;

peso_c=peso-m_peso;

drop _type_ _freq_;

proc print; run;

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:

(22)

0BS M_ALT M_PESO NOME SESSO ETA ALTEZZA PESO ALT_C PESO_C 1 137.818 39 pippo m 32 190 54 52.1818 15 2 137.818 39 paperino m 34 150 50 12.1818 11 3 137.818 39 minnie f 35 145 40 7.1818 1 4 137.818 39 clarabella f 30 180 65 42.1818 26 5 137.818 39 nonna papera f 99 140 55 2.1818 16 6 137.818 39 qui m 8 120 30 -17.8182 -9 7 137.818 39 quo m 8 120 30 -17.8182 -9 8 137.818 39 qua m 8 120 30 -17.8182 -9 9 137.818 39 emy f 8 117 25 -20.8182 -14 10 137.818 39 ely f 8 117 25 -20.8182 -14 11 137.818 39 edy f 8 117 25 -20.8182 -14

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 1 137.818 39 pippo m 32 190 54 52.1818 15

(23)

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)

Gli argomenti delle funzioni possono essere:

- costanti o variabili numeriche - costanti o variabili alfanumeriche

- espressioni comprese quelle in cui compaiono altre funzioni Le funzioni SAS si possono distinguere nelle seguenti classi:

- funzioni aritmetiche

ricordiamo ABS, MIN, MAX, DIM (indica la dimensione di un'array) HBOUND, LBOUND (forniscono i limiti di un'array), ecc.

- funzioni di troncamento - funzioni matematiche

ricordiamo EXP, LOG, GAMMA (funzione Gamma completa), LGAMMA (log. nat. della funz.

Gamma).

- funzioni trigonometriche - funzioni probabilistiche

valore integrale valore quantile POISSON

PROBBETA BETAINV

PROBBNML

PROBCHI CINV

PROBF FINV

PROBGAM GAMINV

PROBNORM PROBIT

PROBT TINV

(con opportuni parametri) - funzioni statistiche

ricordiamo MIN (minimo), MAX (massimo), MEAN (media), N (numero di dati non missing), NMISS (numero di dati missing), RANGE (rango), STD (standard deviation), SUM (somma), VAR (varianza), USS (somma dei quadrati dei dati), CSS (somma dei quadrati dei dati centrati sulla media).

- funzioni per generare numeri casuali

ricordiamo NORMAL (che genera una variabile normale), RANBIN (che genera un'osservazione da una binomiale), RANEXP (che genera una osservazione da un'esponenziale di parametro 1), RAGGAMM, ecc.

- funzioni per elaborazione di stringhe - funzioni per elaborare date e tempi - funzioni di sistema

- funzioni speciali

(24)

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.

PROGRAMMA SAS n. 17 bis:

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

proc means;

run;

The MEANS Procedure

Variable N Mean Std Dev Minimum Maximum ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ t8 3 20.0000000 5.5677644 15.0000000 26.0000000 t12 3 24.0000000 6.0000000 18.0000000 30.0000000 t18 3 23.0000000 5.5677644 18.0000000 29.0000000 media_temp 3 22.3333333 5.6960025 17.0000000 28.3333333 ƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ

F2. VALORI MANCANTI

Il valore di una variabile viene messo a missing se il campo di input è blank oppure è un punto (salvo diversa specificazione di formato).

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.

PROGRAMMA SAS n. 18:

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;

(25)

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, ... .

F3. LE SOMME CUMULATE 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:

RETAIN variabili valori iniziali;

Esempio.

PROGRAMMA SAS n. 19:

DATA ADD;

RETAIN TOTALE 0;

INPUT PUNTEGGI;

TOTALE=TOTALE+PUNTEGGI;

DATALINES;

10 3 7 5

;

PROC PRINT;RUN;

OUTPUT SAS:

OBS TOTALE PUNTEGGI

1 10 10

2 13 3

3 20 7

4 25 5

PROGRAMMA SAS n. 19 bis:

DATA ADD2;

SET ADD;

RETAIN CONTO 0;

CONTO=CONTO+3;

PROC PRINT;RUN;

OUTPUT SAS:

OBS CONTO TOTALE PUNTEGGI

1 3 10 10

2 6 13 3

3 9 20 7

4 12 25 5

(26)

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;

Alcuni esempi che illustrano possibili espressioni sono:

bilancia + (- debito);

somma2 + x*x;

nx + (x ne .);

Con l’ultima istruzione si contano i valori non missing; infatti l’espressione logica (x ne .)vale 1 se è veririficata e 0 altrimenti.

Retain e valori mancanti

PROGRAMMA SAS n. 20:

DATA ADD;

RETAIN CONTO TOTALE 0;

INPUT PUNTEGGI;

TOTALE=TOTALE+PUNTEGGI;

CONTO=CONTO+3;

DATALINES;

10 3 7

. (missing value) 6

4

;

PROC PRINT;RUN;

OUTPUT SAS:

OBS CONTO TOTALE PUNTEGGI

1 3 10 10

2 6 13 3

3 9 20 7

4 12 . .

5 15 . 6

6 18 . 4

Se si volesse avere TOTALE con valore anche per le osservazioni 4, 5 e 6 si dovrebbe fare:

TOTALE = SUM (TOTALE, PUNTEGGI);

Se si omettesse l'istruzione RETAIN le variabili TOTALE e PUNTEGGI avrebbero solo valori missing.

(27)

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

(28)

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 vector (PDV)

is a logical area in memory where SAS builds a data set, one observation at a time.

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 information

is information that SAS creates and maintains about each SAS data set, including data 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.

(29)

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.

Creating the Input Buffer and the Program Data Vector

When DATA step statements are compiled, SAS determines whether to create an input buffer. If the input file contains raw data (as in the example above), SAS creates an input buffer to hold the data before moving the data to the program data vector (PDV). (If the input file is a SAS data set, however, SAS does not create an input buffer. SAS writes the input data directly to the PDV.)

The PDV contains all the variables in the input data set, the variables created in DATA step statements, and the two variables, _N_ and _ERROR_, that are automatically generated for every DATA step. The _N_ variable represents the number of times the DATA step has iterated. The _ERROR_ variable acts like a binary switch whose value is 0 if no errors exist in the DATA step, or 1 if one or more errors exist.

The following figure shows the Input Buffer and the program data vector after DATA step compilation.

Input Buffer and Program Data Vector

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.

(30)

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

Writing an Observation to the SAS Data Set

When SAS executes the last statement in the DATA step, all values in the PDV, except those marked to be dropped, are written as a single observation to the data set TOTAL_POINTS. The following figure shows the first observation in the TOTAL_POINTS data set.

The First Observation in Data Set TOTAL_POINTS

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.

(31)

Current Values in the Program Data Vector

Reading the Next Record

SAS reads the next record into the input buffer. The INPUT statement reads the data values from the input buffer and writes them to the PDV. The Sum statement adds the values of Event1, Event2, and Event3 to TeamTotal. The value of 2 for variable _N_ indicates that SAS is beginning the second iteration of the DATA step. The following figure shows the input buffer, the PDV for the second record, and the SAS data set with the first two observations.

Input Buffer, Program Data Vector, and First Two Observations

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.

When the DATA Step Finishes Executing

The DATA step stops executing after it processes the last input record. You can use PROC PRINT to print the output in the TOTAL_POINTS data set:

Output from the Walkthrough DATA Step

Total Team Scores 1 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

(32)

F5. GLI ARRAY

Gli array sono una struttura logica che non viene conservata nel Data Set ma è utilizzabile solo nel passo di Data nel quale l’array è costruito.

Si usano quando bisogna fare le stesse operazioni su un gran numero di variabili.

ESEMPIO

Si vogliono trasformare le temperature da gradi centigradi a gradi Farhenait PROGRAMMA SAS N. 20 bis :

data temperature;

input citta $ t6 t12 t18;

array t{3} t6--t18;

array tf{3} tf6 tf12 tf18;

do i=1 to 3;

tf{i}=(t{i}*180/100)+32;

end;

drop i;

tot_temp=mean(of t{*});

datalines;

Genova 19 24 22 Milano 15 18 18 Napoli 26 30 29

;

proc print;run;

OUTPUT SAS

Obs citta t6 t12 t18 tf6 tf12 tf18 tot_temp 1 Genova 19 24 22 66.2 75.2 71.6 21.6667 2 Milano 15 18 18 59.0 64.4 64.4 17.0000 3 Napoli 26 30 29 78.8 86.0 84.2 28.3333

Syntax

ARRAY array-name { subscript } <$><length> <array-elements> <(initial-value-list)>;

Arguments 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<)>

(33)

Examples

Example 1: Defining Arrays

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};

Example 2: Assigning Initial Numeric Values

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);

Example 3: Defining Initial Character Values

array test2{*} a1 a2 a3 ('a','b','c');

Example 5: Using Iterative DO-Loop Processing

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;

Example 6: Referencing Many Arrays in One Statement

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;

Example 8: Using the Asterisk References as a Variable List

• array cost{10} cost1-cost10;

totcost=sum(of cost {*});

• array days{7} d1-d7;

input days {*};

• array hours{7} h1-h7;

put hours {*};

Riferimenti

Documenti correlati

4) Costruire tabelle di contingenza a due vie per le variabili ritenute significative.. Analizziamo i dati contenuti nel file di testo strike.txt. I dati riguardano le

If you want to print or save the entire contents of the Output window, first make the Output window active by clicking in it, then select either Print or Save As from the File

PROC SORT: ordina le osservazioni del Sas data set rispetto ad una o più variabili, memorizzando il risultante file ordinato in un nuovo Sas data set

In riferimento alle applicazioni di queste piattaforme in saggi di detection, la rilevazione del fenomeno di binding tra un recettore e il suo analita viene misurato sulla base

Within the component analysis (CA) framework ( Meredith and Millsap 1985 ; Schonemann and Steiger 1976 ), redundancy analysis (RA; Van den Wollenberg 1977 ) is the simplest type

Validation visits are essential to optimise data quality at source, ensure centres are aware of the importance of correct informed consent and encourage dialogue to

La Proc Univariate permette di determinare il valore dei principali indici statistici e inserendo l’opzione normal viene effettuato un test di bontà di adattamento della

Si vuole stabilire se esiste una dipendenza fra il flusso di un corso d’acqua (cioè la quantità di acqua che passa in un minuto) e la profondità del corso d’acqua.. Per ottenere