Introduction au logiciel SAS

50
Introduction au logiciel SAS Aude Tavenard [email protected]

Transcript of Introduction au logiciel SAS

Page 2: Introduction au logiciel SAS

Objectifsducours

•  Connaîtrel’environnementdulogicielSAS•  Manipulerdesdonnées•  Fairedesstatistiquesdescriptives•  Fairedesgraphiques(boxplots/histogrammes/courbes)

Page 3: Introduction au logiciel SAS

LELOGICIEL

Page 4: Introduction au logiciel SAS

PrésentationdeSAS•  Logicieldatede1976initialementdestinéàl’étudestatistiquedesdonnées(SAS=StatisticalAnalysisSystem)

•  AideSAS:https://documentation.sas.com/doc/fr/pgmsascdc/9.4_3.5/pgmsaswlcm/home.htm

•  Différentesfonctionnalitésdéclinéesenmodules.Lespluscourantssont:

Module Descriptiondesprincipalesfonctionnalités

BASE Importation,manipulationetexportationdesdonnées

STAT Ensembledesfonctionnalitésstatistiquescourantesetpoussées

GRAPH Gestiondessortiesgraphiques

Page 5: Introduction au logiciel SAS

EnvironnementSAS•  Différentesfenêtresdisponibles:

ü Programeditorouenhancededitorü Logü Outputü Explorerü Results

•  Programmesü Chaquelignedecodesetermineparunpointvirguleü Descommentairespeuventêtreinclusentrelescaractères/**/

Page 6: Introduction au logiciel SAS

SASStudio•  ViaSASOnDemand:https://welcome.oda.sas.com/home

•  Utiliségratuitementparlesétudiants

•  VersiondeSASenligne•  VoiraideutilisationdeSASOnDemandsurCursus

Page 7: Introduction au logiciel SAS

FichierscréésparSASTables(1/2)•  Unetableestcomposéed’observations(pourleslignes)etdevariables(pourlescolonnes)

•  Contraintespournommerunetable:•  Pasplusde32caractères•  Pasdechiffrecommepremiercaractère•  Nepeutcontenirquedeslettresnonaccentuées,deschiffresetlecaractère«underscore»

Page 8: Introduction au logiciel SAS

FichierscréésparSASTables(2/2)•  AccèsauxdonnéesstockéesdanslerépertoireFichiersdeSASOnDemandenformat.sas7bdatouvuedefichierstemporaires

•  Tables:«photo»desdonnéestellesqu’ellessontenregistréesdanslerépertoireFichiers

àSiunetableestécrasée,lesdonnéesstockéesdanslerépertoireFichierssontaussiimpactées•  UnetablepeutêtreexportéedansSASStudiopourêtreenregistréesurunecléUSBousurunordinateur.

Page 9: Introduction au logiciel SAS

•  LabibliothèqueSAS(oulibrary)désigneunrépertoiredetables

•  L’instructionlibnamesertàassignerunebibliothèque•  Contraintespournommerunetable:•  Pasplusde8caractères•  Pasdechiffrecommepremiercaractère•  Nepeutcontenirquedeslettresnonaccentuées,deschiffresetlecaractère«underscore»

•  CodeSAS:SousUnix:libname donnees "/documents/données/SAS";SousWindows:libname donnees "c:\documents\données\SAS";

FichierscréésparSASBibliothèques

Page 10: Introduction au logiciel SAS

•  SASHELP:contientdesexemplesdeprogrammes,desressourcesutilesauxdifférentsmodulesdeSAS.Bibliothèqueinterditeenécriture

•  SASUSER:contientlesélémentsdepersonnalisationdelasessiondel’utilisateur

•  WORK:peutcontenirdenombreuxfichiersmaisattentionlesfichierssonttemporairesetsontsupprimésàlafindelasessionSAS

FichierscréésparSASBibliothèquesallouéespardéfaut

Page 11: Introduction au logiciel SAS

ProgrammeSAS:étapedataouprocédure•  Etapedata:pourmodifier,fusionner,concaténer,importer,exporterdesdonnées

data tableSAScréée;…instructions lecture de fichier……instructions de calculs…run;

•  Procédure:pourréaliserdestâchesspecifiques.Ilexisteenviron200procéduresdifférentes

CodeSAS:proc nomProcédure data=tableEntree;…instructions…run;

Page 12: Introduction au logiciel SAS

Opérateurs•  Affectation=•  Comparaison:=^=>>=<<=SQL:inlikebetween•  Booléen;NOTAND&OR|XORSQL:Ismissing

Page 13: Introduction au logiciel SAS

Importerdesdonnées•  Donnéesàimportersontdanslefichier/home/u49948743/ages.txtNom;Prenom;Age;TailleDupont;Maurice;67;1.75Durand;Marcel;75;1.73•  Parétapedatadata tab;

infile ‘/home/u49948743/ages.txt’ dlm=";"firstobs=2;input nom $ prenom $ age taille;

run;

•  PROCIMPORTproc import datafile ='/home/u49948743/ages.txt'

out=tab dbms=dlm replace; delimiter=";";getnames=yes;

run;

Page 14: Introduction au logiciel SAS

Exporterdesdonnéesavecétapedata•  Etapedataversfichieràséparateurs:data _null_;

set work.tab;file "/home/u49948743/sortie.csv"; put nom ";" prenom ";" date ";" taille ;

run; •  Etapedataversfichierencolonnes:data _null_;

set work.tab;file "/home/u49948743/dat"; put @15 nom @15 prenom @8 date @15 taille ;

run;

Page 15: Introduction au logiciel SAS

ExporterdesdonnéesavecPROCEXPORTproc export data=work.tab

outfile='/home/u49948743/ages.txt' dbms=dlm replace; delimiter=";";

run;

proc export data=work.taboutfile='/home/u49948743/ages.xls' dbms=excel replace; sheet="feuille1";

run;

Page 16: Introduction au logiciel SAS

Variablesetobservations•  Attributsd’unevariable:•  Nom(mêmescontraintesquelestables:pasplusde32caractèresetc…)

•  Label:décritlavariableen256caractèresmax•  Type:numérique(nombreoudate)vscaractère•  Format:permetdeprésenterl’informationcontenuedanslesdonnéesstockéessousuneformespécifique.Peutserviràpréciserlenombrededécimales,choisirunformatdedatesetc…

•  Informat•  Longueur

•  SAScodedansétapedata:attrib

nomVariable1 label="texte" format=format. length=$12nomVariable2 label="texte" format=format. length=$12

;

Page 17: Introduction au logiciel SAS

FormatsNomduformat Valeurstockée Format Valeuraffichée

$x. ABcdEF $3. ABc

$UPCASEx. ABcdEF $UPCASE5. ABCDE

x.x 1234.345 5.1 1234.3

DDMMYY10. 15000* DDMMYY10. 25/01/2001

YEAR4. 15000 YEAR4. 2001

FRADFWDX. 15000 FRADFWDX. 25janvier2001

*lesdatessontstockéesennombredejourdepuisle01/01/1960

Page 18: Introduction au logiciel SAS

Etapedata:calculsdata tab2;

set tab; index=_N_; expage=exp(age); calcul=taille+4*poids**2; mediane=median(age,calcul,poids);

run;

Page 19: Introduction au logiciel SAS

Etapedata:sélectiondevariablesdata tab2;

set tab; drop poids; /*suppression*/keep nom; /*conservation*/

run; oudata tab2;

set tab (drop=poids keep=nom); run;

Page 20: Introduction au logiciel SAS

Etapedata:sélectiond’observationsdata tab2;

set tab (where = (prenom="Jean")) ; run;

Page 21: Introduction au logiciel SAS

Etapedata:ifthenelsedata tab2;

set tab; if age>60 then age_cat="1"; else age_cat="2";

run;

Page 22: Introduction au logiciel SAS

ConcaténerdesdonnéesConcaténationverticaledata tab;

set tab1 tab2;run;

tab1

tab2

tab1

tab2

Page 23: Introduction au logiciel SAS

ConcaténerdesdonnéesConcaténationhorizontaledata tab;

merge tab1 tab2;run;

tab1

tab2

tab1

tab2

Page 24: Introduction au logiciel SAS

Fusionnerdesdonnéesproc sort data=tab1; by id; run;proc sort data=tab2; by id; run;data tab;

merge tab1 tab2;by id;

run;

tab1

tab2

tab1

tab2

Page 25: Introduction au logiciel SAS

Suiteétapedata:renommerunevariabledata tab2;

set biblio.tab; rename id=patient;

run;

ou

data tab2; set biblio.tab (rename= (id=patient)) ;

run;

Page 26: Introduction au logiciel SAS

Suiteétapedata:filtresurlesdatesdata tab2;

set biblio.tab; where date>"01APR2020"d;

run;

oudata tab2;

set biblio.tab; where date>mdy(4,1,2020);

run;

Page 27: Introduction au logiciel SAS

Suiteétapedata:créationd’uncompteur(1/2)data tab2;

set biblio.tab; retain compteur;

if _N_=1 then compteur=0; compteur=compteur+1;

run;

ID Compteur

001 1

001 2

001 3

002 4

002 5

_N_=1

Page 28: Introduction au logiciel SAS

Suiteétapedata:créationd’uncompteur(2/2)data tab2;

set biblio.tab; retain dateInscription;

if first.id then dateInscription=dateAchat; delai=dateAchat-dateInscription;

run;

ID dateAchat dateInscription delai

001 23/04/2020 23/04/2020 0001 14/06/2020 23/04/2020 52001 17/07/2020 23/04/2020 85002 12/03/2020 12/03/2020 0002 18/05/2020 18/05/2020 67

Page 29: Introduction au logiciel SAS

FonctionsutilesFonctions Description Appel Exemple

substr() Extraitunechaînedecaractères

substr(varCar,debut,longueur)

substr(numsecu,1,1)à2

upcase() Ecritencapital upcase(varCar) upcase(ville)à"RENNES"

index() Indiquesiunmotestprésentdansunechaînedecaractèresendonnantlapositiondudébutdumot

index(varCar,"mot") adresse="11rued’Antrain»index(adresse,"rue")à4

put() Convertitunevariablenumériqueenvariablecaractère

put(varNum,format.) x=1put(x,best12.)à"1"

input() Convertitunevariablecaractèreenvariablenumérique

input(varCar,informat.) x="1"input(x,$10.)à1

Page 30: Introduction au logiciel SAS

LESPROCEDURES

Page 31: Introduction au logiciel SAS

PROCSORT:tri•  Procédurequipermetdetrierproc sort data=biblio.tab out=tableTriée;

by listeVariables; /*ordre croissant*/run;

proc sort data=biblio.tab out=tableTriée;by descending listeVariables; /*ordre

décroissant*/run;

Page 32: Introduction au logiciel SAS

PROCSORT:gestiondesdoublonsproc sort data=biblio.tab

out=tableTriée /*sans doublons*/dupout=tableDoublons /*doublons

uniquement*/nodupkey;by listeVariables;

run;

noduplicate: cherchelesobservationssimilairespourtouteslesvariablesdanslatable

Rechercheobservationsquiontlesmêmesvaleurspourtouteslesvariablescitéesdansl’instructionby

Page 33: Introduction au logiciel SAS

PROCMEANS•  Variablenumérique•  Statistiquesdescriptivespardéfaut:nombred’observations,moyenne,écarttype,minimum,maximum

proc means data=biblio.tab;var variableNumerique;

run;•  Possibilitéd’ajouterd’autresstatistiques:médiane,Q1,Q3,etc…proc means data=biblio.tab median Q1 Q3;

var variableNumerique;run;•  Instructionclasspermetdecalculerlesstatistiquesdescriptivesparsousgroupes

•  Voiraussiproc univariate

Page 34: Introduction au logiciel SAS

PROCFREQ•  Trisàplatoutriscroisés•  Tableauàunevariable:proc freq data=biblio.tab;

table sexe;run;•  Tableaucroisé:proc freq data=biblio.tab;

table variableLignes*variableColonnes;run;•  TestduChi-2:proc freq data=biblio.tab;

table variableLignes*variableColonnes/CHISQ;run;

Page 35: Introduction au logiciel SAS

PROCTABULATE(1/2)•  Créationdefréquencesoudestatistiquesdescriptives

proc tabulate data=biblio.tab;class variableLigne variableColonne;var variablePonderation;table (variableLigne), (variableColonne)* (variablePonderation)* (statistiques);

run;

Page 36: Introduction au logiciel SAS

PROCTABULATE(2/2)proc tabulate data=biblio.tab;

class region zone;var temperature;table (region), (zone)*(temperature)*(mean, min, max);

run;

zone(rurale) zone(urbaine)

region mean min max mean min max

Bretagne 21.2 3 34 23.5 5 36

Occitanie 26.7 9 38 28.1 11 41

IledeFrance 23.6 4 37 24.7 6 40

Page 37: Introduction au logiciel SAS

PROCPRINT•  Créationdelistingouéditiond’unetableSASproc print data=biblio.tab label noobs;

var nom prenom sexe;run;

•  Optionlabel:permetd’afficherlelabeldesvariables•  Option noobs:permetdesupprimerlenumérodel’observationdanslasortie

Page 38: Introduction au logiciel SAS

ODS:OutputDeliverySystem•  ODSpermet:

ü Afficherunepartiedessortiesü Sortirlesrésultatsversdifférentsformats(pagewek,documentWord,feuilleExcel,etc…)

ü CréeruneouplusieurstablesSASensortiedesprocédures•  Instructionquipermetdetracertouteslestablesdisponiblesensortieenutilisantl’ODS:ods trace on;

•  Instructionquipermetdestopperceslistes:ods trace off;

•  Lestablesdisponiblessontlistéesdanslejournal(log)

Page 39: Introduction au logiciel SAS

ODSoutput•  Instructionodsoutputpermetd’enregistrerunetablecrééeparlaprocédure

•  Exemple:Résultatdel’odstraceonsurlaPROCMEANS:

Enregistrementdelatableconcernée:ods output summary=work.resultats;proc means data=biblio.tab;

var variableNumerique;run;

Page 40: Introduction au logiciel SAS

ODS:créationdesortiesWord,Excel,PDF•  ODSpermetaussidecréerdessortiesWord,Excel,PDFoùserontécritestouteslestablescrééesparlesprocédures

•  Ilexistedifférentsstylespourlessortiesstyle=•  Instruction:ods html file="chemin du fichier.xls"; /*excel*/

code de la procédure…ods html close;ods rtf file="chemin du fichier.rtf"; /*word*/

code de la procédure…ods rtf close;ods pdf file="chemin du fichier.pdf"; /*PDF*/

code de la procédure…ods pdf close;

Page 41: Introduction au logiciel SAS

MiseenformedessortiesSAS•  Pourorganiserlesrésultats,onpeututiliserdestitresetpiedsdepageenutilisantlesinstructions:

title "Titre des résultats »;footnote "Abbreviations utiles:… »;

Page 42: Introduction au logiciel SAS

ODSGRAPHICSODS RTF BODY=’nomfichier.rtf’; ODS GRAPHICS ON;

/* Programme SAS */ODS GRAPHICS OFF; ODS RTF CLOSE;

Page 43: Introduction au logiciel SAS

PROCUNIVARIATE

Page 44: Introduction au logiciel SAS

PROCBOXPLOT

Page 45: Introduction au logiciel SAS

PROCSGPLOT(1/3)

Page 46: Introduction au logiciel SAS

PROCSGPLOT(2/3)

Page 47: Introduction au logiciel SAS

PROCSGPLOT(3/3)•  Beaucoupd’optionspossibles,lienutile:https://od-datamining.com/knwbase/la-procedure-sgplot-sa-vie-son-oeuvre/

Page 48: Introduction au logiciel SAS

PROCSGPIE

Page 49: Introduction au logiciel SAS

PROCSGPANEL

Page 50: Introduction au logiciel SAS

Autresprocédures•  Ilexisted’autresprocéduresplusanciennes,moinspuissantes,quinesontpasdisponiblesdansSASstudio:•  PROCGBARLINE:histogrammesetcourbes•  PROCGPLOT:nuagesdepointsetcourbes•  PROCGCHART:graphiquesenbâtons,diagrammescirculaires