资源描述:
《sas programming manipulation data with the data setp》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
®SASProgrammingII:ManipulatingDatawiththeDATAStepCourseNotes iiForYourInformation®SASProgrammingII:ManipulatingDatawiththeDATAStepCourseNoteswasdevelopedbyJCheemaandMelindaThielbar.AdditionalcontributionsweremadebyMartyHultgren,KentReeve,WarrenRepole,andRogerStaum.EditingandproductionsupportwasprovidedbytheCurriculumDevelopmentandSupportDepartment.SASandallotherSASInstituteInc.productorservicenamesareregisteredtrademarksortrademarksofSASInstituteInc.intheUSAandothercountries.®indicatesUSAregistration.Otherbrandandproductnamesaretrademarksoftheirrespectivecompanies.®SASProgrammingII:ManipulatingDatawiththeDATAStepCourseNotesCopyright©2007SASInstituteInc.Cary,NC,USA.Allrightsreserved.PrintedintheUnitedStatesofAmerica.Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,ortransmitted,inanyformorbyanymeans,electronic,mechanical,photocopying,orotherwise,withoutthepriorwrittenpermissionofthepublisher,SASInstituteInc.BookcodeE70307,coursecodePROG2,prepareddate16Apr2007.PROG2_008ISBN978-1-59994-397-8 ForYourInformationiiiTableofContentsCourseDescription......................................................................................................................viPrerequisites...............................................................................................................................viiChapter1Introduction..........................................................................................1-11.1Overview..........................................................................................................................1-31.2ReviewofSASBasics.....................................................................................................1-91.3ReviewofDATAStepProcessing..................................................................................1-191.4ReviewofDisplayingSASDataSets............................................................................1-341.5WorkingwithExistingSASDataSets...........................................................................1-431.6PrerequisiteSyntax(Self-Study)....................................................................................1-671.7NavigatingtheSASWindowingEnvironment(Self-Study).........................................1-70Chapter2ControllingInputandOutput..............................................................2-12.1OutputtingMultipleObservations...................................................................................2-32.2WritingtoMultipleSASDataSets................................................................................2-202.3SelectingVariablesandObservations............................................................................2-272.4WritingtoanExternalFile.............................................................................................2-452.5SolutionstoExercises....................................................................................................2-68Chapter3SummarizingData................................................................................3-13.1CreatinganAccumulatingTotalVariable........................................................................3-33.2AccumulatingTotalsforaGroupofData......................................................................3-173.3SolutionstoExercises....................................................................................................3-43 ivForYourInformationChapter4ReadingandWritingDifferentTypesofData.....................................4-14.1ReadingDelimitedRawDataFiles..................................................................................4-34.2ControllingwhenaRecordLoads.................................................................................4-464.3ReadingHierarchicalRawDataFiles............................................................................4-884.4SolutionstoExercises..................................................................................................4-154Chapter5DataTransformations...........................................................................5-15.1Introduction......................................................................................................................5-35.2ManipulatingCharacterValues........................................................................................5-85.3ManipulatingNumericValues.......................................................................................5-555.4ManipulatingNumericValuesBasedonDates..............................................................5-655.5ConvertingVariableType..............................................................................................5-705.6SolutionstoExercises....................................................................................................5-95Chapter6DebuggingTechniques(Self-Study)...................................................6-16.1UsingthePUTStatement.................................................................................................6-36.2UsingtheDEBUGOption.............................................................................................6-15Chapter7ProcessingDataIteratively..................................................................7-17.1DOLoopProcessing........................................................................................................7-37.2SASArrayProcessing....................................................................................................7-377.3UsingSASArrays..........................................................................................................7-527.4SolutionstoExercises....................................................................................................7-75®Chapter8CombiningSASDataSets.................................................................8-18.1Match-MergingTwoorMoreSASDataSets..................................................................8-38.2SimpleJoinsUsingtheSQLProcedure(Self-Study)....................................................8-27 ForYourInformationv8.3SolutionstoExercises....................................................................................................8-41Chapter9LearningMore.......................................................................................9-19.1WhereDoIGoFromHere?.............................................................................................9-39.2SASResources.................................................................................................................9-5AppendixAIndex.....................................................................................................A-1 viForYourInformationCourseDescriptionThisintermediatecoursefocusesonhowtomanageSASdatasetinputandoutput,workwithdifferentdatatypes,andmanipulatedata.Specifically,thecoursediscussesusingtheDATAsteptocontrolSASdatasetinputandoutput,combineSASdatasets,summarizedata,processdataiterativelywithDOloopsandarrays,andperformdatamanipulationsandtransformations.Tolearnmore…Afullcurriculumofgeneralandstatisticalinstructor-basedtrainingisavailableatanyoftheInstitute’strainingfacilities.Instituteinstructorscanalsoprovideon-sitetraining.Forinformationonothercoursesinthecurriculum,contacttheSASEducationDivisionat1-800-333-7660,orsende-mailtotraining@sas.com.YoucanalsofindthisinformationontheWebatsupport.sas.com/training/aswellasintheTrainingCourseCatalog.ForalistofotherSASbooksthatrelatetothetopicscoveredinthisCourseNotes,USAcustomerscancontactourSASPublishingDepartmentat1-800-727-3228orsende-mailtosasbook@sas.com.CustomersoutsidetheUSA,pleasecontactyourlocalSASoffice.Also,seethePublicationsCatalogontheWebatsupport.sas.com/pubsforacompletelistofbooksandaconvenientorderform. ForYourInformationviiPrerequisitesBeforeattendingthiscourse,youshouldhaveatleastsixmonthsofexperiencewritingSASprogramsor®havecompletedtheSASProgrammingI:EssentialscourseandusedSASforatleastonemonth.Specifically,youshouldbeableto•createandaccessfilesinyouroperatingenvironment•explainthestructureofaSASprogram•explorethestructureandcontentsofaSASdataset•distinguishbetweensyntaxanddataerrors•debugaSASprogram•createaSASdatasetfromafixed-formatexternalfile•subsettherowsandcolumnsofaSASdataset•createderivedvariables•writeconditionallogicstatements•readandwriteSASdatevalues•accessSASdatalibraries•sortaSASdataset•readoneormoreSASdatasetsusingaSETstatement•performasimplemergeusingaMERGEstatement•createdetailandsummaryreportsfromaSASdataset•placetitlesandfootnotesonreports. viiiForYourInformation Chapter1Introduction1.1Overview..........................................................................................................................1-31.2ReviewofSASBasics....................................................................................................1-91.3ReviewofDATAStepProcessing...............................................................................1-191.4ReviewofDisplayingSASDataSets..........................................................................1-341.5WorkingwithExistingSASDataSets.........................................................................1-431.6PrerequisiteSyntax(Self-Study).................................................................................1-671.7NavigatingtheSASWindowingEnvironment(Self-Study)......................................1-70 1-2Chapter1Introduction 1.1Overview1-31.1OverviewObjectives¢ExplorethefunctionalityoftheDATAstep.3WhyUsetheDATAStep?TheDATAsteppermitstrueprogrammingfunctionality.Itis¢flexible¢accessible.TheDATAstepispartofBaseSASsoftware,whichmakesitavailableonalloperatingsystemsandforallSASusers.4 1-4Chapter1IntroductionWhatCantheDATAStepDo?YoucanusetheDATAstepinthefollowingwaystotransformyourinformation:¢ReadfromarawdatafileintotheSASSystem.SASDataSetRawDataFileDescriptorDATAStep5WhatCantheDATAStepDo?¢CreatemultipleSASdatasetsinoneDATAstep.DATAStep6 1.1Overview1-5WhatCantheDATAStepDo?¢Rotateadataset.IDQtr1Qtr2Qtr3Qtr4IDQtr1Qtr2Qtr3Qtr4E00224123322.E00224123322.E0036735484030E0036735484030IDQtrAmountIDQtrAmountE00224112E00224233E00224322E002244.E00367135E00367248E00367340E003674307WhatCantheDATAStepDo?¢Combineexistingdatasets.SASDataSet1SASDataSet2DATAStep8 1-6Chapter1IntroductionWhatCantheDATAStepDo?Youcanalsoaddoraugmentinformationinavarietyofways.¢Createaccumulatingtotals.SaleSaleSaleDateAmtSaleDateAmtMth2DteMth2Dte01APR2001498.4901APR2001498.49498.49498.4902APR2001946.5002APR2001946.501444.991444.9903APR2001994.9703APR2001994.972439.962439.9604APR2001564.5904APR2001564.593004.553004.5505APR2001783.0105APR2001783.013787.563787.569WhatCantheDATAStepDo?¢Manipulatenumericvalues.BirthDay4253MonthSASFunction810 1.1Overview1-7WhatCantheDATAStepDo?¢Manipulatecharactervalues.HappyBirthDayHappyBirthDayHappy30thBirthday!30thHappy29thBirthday!29thSASFunction11WhatCantheDATAStepDo?¢Summarizedatasets.SalaryDivSalaryDiv42000HUMRESDivDivSalDivDivSal42000HUMRES34000FINACE34000FINACE27000FLTOPSDATAStepFINACE73000FINACE7300027000FLTOPS20000FINACEFLTOPS46000FLTOPS4600020000FINACE19000FINACEHUMRES42000HUMRES4200019000FINACE19000FLTOPS19000FLTOPS12 1-8Chapter1IntroductionAndmuch,muchmore.13 1.2ReviewofSASBasics1-91.2ReviewofSASBasicsObjectives¢ReviewfundamentalSASconcepts.¢ReviewcreatingaSASdatasetfromarawdatafile.15IndustryTerminologyComparisonDataProcessingSASSystemSQLfiledatasettablerecordobservationrowfieldvariablecolumn16 1-10Chapter1IntroductionStructureofSASDataSetsSASDataSetGeneralDataSetInformationNameNumberofObs.*LabelNumberofVariablesDescriptorDate/TimeCreatedPortionStorageInformationInformationforEachVariableNameTypeLengthPosition*Label*Format*InformatIDNUMNAMEWAGECATWAGERATE1351Farr,SueS3392.50161S5093.75Data212Moore,RonS.Portion2512Ruth,GHS1572.50.........5151Coxe,SusanS3163.0017AttributesofSASVariablesAllSASvariableshavethreerequiredattributes:¢name¢type¢length18 1.2ReviewofSASBasics1-11VariableNamesTherulesfornamingSASdatasetsandvariablesarethesame.Names¢mustbe1to32charactersinlength¢muststartwithaletter(A-Z)oranunderscore(_)¢cancontinuewithanycombinationofnumbers,letters,andunderscores.19InSASVersion8andhigher,SASvariablenamesaredisplayedinthecasethattheyarecreated.However,asinallversionsofSAS,variablenamesarenotcase-sensitivewithintheprogram.Thisenablesyoutocreatevariablenamesthatareeasiertoreadinreportswithoutworryingaboutcase-sensitivitywithinyourSASprograms. 1-12Chapter1IntroductionVariableTypeandLengthVariablescanbeCharacterCharacter(1to32K)(1to32K)NumericNumericbydefault,storedinfloatingpointbydefault,storedinfloatingpointrepresentationusing8bytesrepresentationusing8bytes20!Itispossibletostorenumericvariablesusingfewerthan8bytes.However,reducingthelengthofnumericvariablesdecreasestheirprecisionandcanyieldunexpectedresults.SASDatesSASdatesarespecialnumericvaluesrepresentingthenumberofdaysbetweenJanuary1,1960,andaspecifieddate.1jan19591jan19601jan19611jan2000DATE9.Informatstore-36503661461021... 1.2ReviewofSASBasics1-13SASDatesSASdatesarespecialnumericvaluesrepresentingthenumberofdaysbetweenJanuary1,1960,andaspecifieddate.1jan19591jan19601jan19611jan2000DATE9.Informatstore-365036614610displayMMDDYY10.Format01010101/0/0/0/01/1/1/1/191919205960610022CreateaSASDataSetfromaRawDataFileE123215OCT199961065ArawdatafilecontainsE234101JUN199791688employeeinformationforE345226OCT199332639thelevel1flightattendants.E678116SEP199228305UsetherawdatafiletoE832126NOV199640440createthework.fltat1E105227FEB199739461SASdataset.E106210MAY198741463E817206JAN200040650E109120AUG19914095023 1-14Chapter1IntroductionDesiredOutputHireObsEmpIDDateSalaryBonus1E123214532610653053.252E234113666916884584.403E345212352326391631.954E678111947283051415.255E832113479404402022.006E105213572394611973.057E10629991414632073.158E817214615406502032.509E109111554409502047.50Bonusis5%oftheSalaryvalue24TheDATAStatementADATAstepalwaysbeginswithaDATAstatement.GeneralformofaDATAstatement:DATADATASAS-data-setSAS-data-set;;TheDATAstatementstartstheDATAstepandnamestheSASdatasetbeingcreated.25 1.2ReviewofSASBasics1-15TheINFILEStatementIfyouarereadingdatafromarawdatafile,youneedanINFILEstatement.GeneralformofanINFILEstatement:INFILEINFILE'raw-data-file'raw-data-file'';;TheINFILEstatementpointstotherawdatafilebeingread.OptionsintheINFILEstatementaffecthowSASreadstherawdatafile.26TheINPUTStatementWhenyoureadfromarawdatafile,theINPUTstatementfollowstheINFILEstatement.GeneralformofanINPUTstatement:INPUTINPUTvariable-specificationvariable-specification…;…;TheINPUTstatementdescribestherawdatafieldsandspecifieshowyouwantthemconvertedintoSASvariables.27 1-16Chapter1IntroductionFormattedInputThisinputstyletellsSASwheretofindthefieldsandhowtoreadthemintoSAS.INPUTINPUT@@nvariable-nameinformat....nvariable-nameinformat....;;@nmovesthepointertothestartingpositionofthefield.variable-namenamestheSASvariablebeingcreated.informatspecifieshowmanypositionstoreadandhowtoconverttherawdataintoaSASvalue.28TheINPUTStatementCommonSASinformats:$w.readsastandardcharacterfield,wherewspecifiesthewidthofthefieldinbytes.w.readsastandardnumericfield,wherewspecifiesthewidthofthefieldinbytesanddspecifiesthenumberofimplieddecimalpositions.DATE9.readsdatesintheform31DEC2012.29Aninformatisareadinginstruction.Theinformatthatisuseddependsontheformofthefieldintherawdatafile.UnlesstheseattributesarespecifiedbeforetheINPUTstatement,SASusestheinformattosetthetypeandlengthofthevariablesyoureadfromtherawdatafile.ForacompletelistofSASinformats,seetheSASdocumentation. 1.2ReviewofSASBasics1-17TheAssignmentStatementTocreateanewvariableintheDATAstep,useanassignmentstatement:variable-namevariable-name==expressionexpression;;TheassignmentstatementcreatesaSASvariableandspecifieshowtocalculatethatvariable'svalue.30CreateaSASDataSetfromaRawDataFiledatawork.fltat1;infile'raw-data-file';input@1EmpID$5.@7HireDatedate9.@17Salary5.;Bonus=.05*Salary;run;31 1-18Chapter1IntroductionCreateaSASDataSetfromaRawDataFilePartialLogNOTE:9recordswerereadfromtheinfile'fltat1.dat'.Theminimumrecordlengthwas21.Themaximumrecordlengthwas21.NOTE:ThedatasetWORK.FLTAT1has9observationsand4variables.c01s2d1.sas32 1.3ReviewofDATAStepProcessing1-191.3ReviewofDATAStepProcessingObjectives¢ReviewthetwophasesofDATAstepprocessing.34CreateaSASDataSetfromRawDatadatawork.fltat1;infile'raw-data-file';input@1EmpID$5.@7HireDatedate9.@17Salary5.;Bonus=.05*Salary;run;35 1-20Chapter1IntroductionProcessingtheDATAStepTheSASSystemprocessestheDATAstepintwophases:¢compilation¢execution.36CompilationDuringcompilation,SAS¢checkscodeforsyntaxerrors¢translatescodetomachinecode¢establishesanareaofmemorycalledtheinputbufferifreadingrawdata¢establishesanareaofmemorycalledtheprogramdatavector(PDV)¢assignsrequiredattributestovariables¢createsthedescriptorportionofthenewdataset.37 1.3ReviewofDATAStepProcessing1-21CompilingtheDATAStepdatawork.fltat1;infile'raw-data-file';input@1EmpID$5.@7HireDateDate9.@17Salary5.;Bonus=.05*Salary;run;38...CompilingtheDATAStepdatawork.fltat1;infile'raw-data-file';input@1EmpID$5.@7HireDateDate9.@17Salary5.;Bonus=.05*Salary;run;InputBuffer39... 1-22Chapter1IntroductionCompilingtheDATAStepdatawork.fltat1;infile'raw-data-file';input@1EmpID$5.@7HireDateDate9.@17Salary5.;Bonus=.05*Salary;run;InputBufferPDVEmpID$540...CompilingtheDATAStepdatawork.fltat1;infile'raw-data-file';input@1EmpID$5.@7HireDateDate9.@17Salary5.;Bonus=.05*Salary;run;InputBufferPDVEmpIDHireDate$5N841... 1.3ReviewofDATAStepProcessing1-23CompilingtheDATAStepdatawork.fltat1;infile'raw-data-file';input@1EmpID$5.@7HireDateDate9.@17Salary5.;Bonus=.05*Salary;run;InputBufferPDVEmpIDHireDateSalary$5N8N842...CompilingtheDATAStepdatawork.fltat1;infile'raw-data-file';input@1EmpID$5.@7HireDateDate9.@17Salary5.;Bonus=.05*Salary;run;InputBufferPDVEmpIDHireDateSalaryBonus$5N8N8N843... 1-24Chapter1IntroductionCompilingtheDATAStepdatawork.fltat1;infile'raw-data-file';input@1EmpID$5.@7HireDateDate9.@17Salary5.;Bonus=.05*Salary;run;InputBufferPDVEmpIDHireDateSalaryBonusfltat1descriptorportionEmpIDHireDateSalaryBonus44$5N8N8N8ExecutionDuringtheexecutionphase,SAS¢initializesthePDVtomissing¢readsdatavaluesintothePDV¢executesassignmentstatementsandconditionalprocessing¢writestheobservationinthePDVtotheoutputSASdatasetattheendoftheDATAstep(bydefault)¢returnstothetopoftheDATAstep¢initializesanyvariablesthatarenotreadfromaSASdatasettomissing(bydefault)¢repeatstheprocess.45 1.3ReviewofDATAStepProcessing1-25TheDATAStepIsaLoopInitializeInitializePDVPDVYESStopExecuteExecuteEndofDATA“read”statement“read”statementfile?stepExecuteNOExecuteprogramstatementsprogramstatementsOutputobservationtoOutputobservationtoSASdatasetSASdataset46ExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;InputBufferInitializePDVtomissingPDVEmpIDHireDateSalaryBonus145..32610..653053..2547... 1-26Chapter1IntroductionExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;InputBufferPDVEmpIDHireDateSalaryBonus145..32610..653053..2548...ExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;InputBufferE123215OCT199961065PDVEmpIDHireDateSalaryBonus145..32610..653053..2549... 1.3ReviewofDATAStepProcessing1-27ExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;InputBufferE123215OCT199961065PDVEmpIDHireDateSalaryBonusE1232145..32610..653053..2550...ExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;InputBufferE123215OCT199961065PDVEmpIDHireDateSalaryBonusE123214532.610..653053..2551... 1-28Chapter1IntroductionExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;InputBufferE123215OCT199961065PDVEmpIDHireDateSalaryBonusE123214532.61065.3053..2552...ExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;.05*61065InputBufferE123215OCT199961065PDVEmpIDHireDateSalaryBonusE123214532.61065.3053.25.53... 1.3ReviewofDATAStepProcessing1-29ExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;InputBufferAutomaticoutputE123215OCT199961065PDVEmpIDHireDateSalaryBonusE123214532.61065.3053.25.54Writefirstobservationtowork.fltat1....ExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;AutomaticreturnInputBufferE123215OCT199961065PDVEmpIDHireDateSalaryBonusE123214532.61065.3053.25.55... 1-30Chapter1IntroductionExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;InputBufferReinitializePDV.ValuesofvariablesnotreadfromE123215OCT199961065SASaresettomissing.PDVEmpIDHireDateSalaryBonus136..66916..884584..4056...ExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;InputBufferE123215OCT199961065PDVEmpIDHireDateSalaryBonus136..66916..884584..4057... 1.3ReviewofDATAStepProcessing1-31ExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;InputBufferE234101JUN199791688PDVEmpIDHireDateSalaryBonus136..66916..884584..4058...ExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;InputBufferE234101JUN199791688PDVEmpIDHireDateSalaryBonusE234113666.91688.4584..4059... 1-32Chapter1IntroductionExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;.05*91688InputBufferE234101JUN199791688PDVEmpIDHireDateSalaryBonusE234113666.91688.4584.40.60...ExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;InputBufferAutomaticoutputE234101JUN199791688PDVEmpIDHireDateSalaryBonusE234113666.91688.4584.40.61Writesecondobservationtowork.fltat1.... 1.3ReviewofDATAStepProcessing1-33ExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065@7HireDatedate9.E234101JUN199791688@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;AutomaticreturnInputBufferE234101JUN199791688PDVEmpIDHireDateSalaryBonusE234113666.91688.4584.40.62...ExecutingtheDATAStepdatawork.fltat1;infile'raw-data-file';RawDataFileinput@1EmpID$5.E123215OCT199961065Continueprocessing@7HireDatedate9.E234101JUN199791688untilendoftherawdatafile@17Salary5.;E345226OCT199332639Bonus=.05*Salary;E678116SEP199228305run;InputBufferE234101JUN199791688PDVEmpIDHireDateSalaryBonus136..66916..884584..4063 1-34Chapter1Introduction1.4ReviewofDisplayingSASDataSetsObjectives¢ReviewproceduresthatdisplaySASdatasets.65 1.4ReviewofDisplayingSASDataSets1-35CreateaSASDataSetfromRawDatadatawork.fltat1;infile'raw-data-file';input@1EmpID$5.@7HireDatedate9.@17Salary5.;Bonus=.05*Salary;run;66CreateaSASDataSetfromRawDataPartialLogNOTE:9recordswerereadfromtheinfile'fltat1.dat'.Theminimumrecordlengthwas21.Themaximumrecordlengthwas21.NOTE:ThedatasetWORK.FLTAT1has9observationsand4variables.67 1-36Chapter1IntroductionViewingaSASDataSetYoucanusethe¢CONTENTSproceduretodisplaythedescriptorportionofaSASdataset¢PRINTproceduretodisplaythedataofaSASdataset.68GeneralformofaPROCCONTENTSstep:PROCCONTENTSDATA=SAS-data-set;RUN;GeneralformofaPROCPRINTstep:PROCPRINTDATA=SAS-data-set;RUN; 1.4ReviewofDisplayingSASDataSets1-37ViewingtheDescriptorPortionproccontentsdata=work.fltat1;run;PartialOutput---AlphabeticListofVariablesandAttributes---#VariableTypeLenƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ4BonusNum81EmpIDChar52HireDateNum83SalaryNum869ViewingtheDataPortionprocprintdata=work.fltat1;run;PartialOutputHireObsEmpIDDateSalaryBonus1E123214532610653053.252E234113666916884584.403E345212352326391631.954E678111947283051415.255E832113479404402022.0070 1-38Chapter1IntroductionTheNOOBSOptionTheNOOBSoptioninthePROCPRINTstatementsuppressestheobservationnumbersinthelistreport.GeneralformoftheNOOBSoption:PROCPRINTPROCPRINTDATA=DATA=SAS-data-setSAS-data-setNOOBSNOOBS;;RUN;RUN;71ViewingtheDataPortionprocprintdata=work.fltat1noobs;run;PartialOutputHireEmpIDDateSalaryBonusE123214532610653053.25E234113666916884584.40E345212352326391631.95E678111947283051415.2572 1.4ReviewofDisplayingSASDataSets1-39TheFORMATStatementTheFORMATstatementappliesaSASformattospecifiedvariables.Aformatcontrolshowdatavaluesaredisplayed.GeneralformofaFORMATstatement:FORMATFORMATSAS-variable(s)format-name.…SAS-variable(s)format-name.…;;YoucanformatasmanyvariablesasyouneedusingoneFORMATstatement.73SASFormatsGeneralformofaSASformat:<<$$>FORMAT-NAMEw.>FORMAT-NAMEw.¢$indicatesacharacterformat.¢FORMAT-NAMEisthenameoftheformat.¢wspecifiesthetotalnumberofcharactersavailablefordisplayingthevalue.¢.istherequireddelimiter.¢dspecifiesthenumberofdecimalplacestobedisplayedforanumericvalue.74 1-40Chapter1IntroductionCommonSASFormatsExamplesofformats:COMMAw.daddscommastonumericvaluesExample:46,543DOLLARw.daddscommasandadollarsigntonumericvalues.Example:$46,543MMDDYY10.writesdatesintheform12/31/201275 1.4ReviewofDisplayingSASDataSets1-41ApplyingaFormatprocprintdata=work.fltat1noobs;formatHireDatemmddyy10.SalaryBonusdollar7.;run;PartialOutputEmpIDHireDateSalaryBonusE123210/15/1999$61,065$3,053E234106/01/1997$91,688$4,584E345210/26/1993$32,639$1,632E678109/16/1992$28,305$1,415E832111/26/1996$40,440$2,02276Formatsassignedinaprocedurearetemporary;theyonlyremainforthatprocedure.AFORMATstatementinaDATAstepassignstheformatpermanentlyandmakesitavailablewheneverthedatasetisused.Forexample,thefollowingcodeassignspermanentformatstothevariablesSalary,Bonus,andHireDate:datawork.fltat1;infile'raw-data-file';input@1EmpID$5.@7HireDatedate9.@17Salary5.;Bonus=Salary*.05;formatHireDatemmddyy10.SalaryBonusdollar7.;run; 1-42Chapter1IntroductionTheVARStatementTocontrolwhichvariablesaredisplayedandtheorderinwhichtheyaredisplayed,usetheVARstatement.GeneralformofaVARstatement:VARVARSAS-variable(s)SAS-variable(s)…;…;77TheVARStatementprocprintdata=work.fltat1noobs;formatSalaryBonusdollar7.;varEmpIDBonusSalary;run;PartialOutputEmpIDBonusSalaryE1232$3,053$61,065E2341$4,584$91,688E3452$1,632$32,639E6781$1,415$28,305E8321$2,022$40,440E1052$1,973$39,46178c01s4d1.sas 1.5WorkingwithExistingSASDataSets1-431.5WorkingwithExistingSASDataSetsObjectives¢ReviewtheconceptofSASdatalibraries.¢ReviewtheLIBNAMEstatement.¢ReviewcreatinganewSASdatasetfromanexistingdataset.¢Reviewconditionalprocessing.80SASFilesSASdatasetsandotherfilesarestoredinSASdatalibraries.WORKSASUSERPROG281 1-44Chapter1IntroductionSASDataLibrariesASASdatalibraryisacollectionofSASfilesthatarerecognizedasaunitbySASonyouroperatingenvironment.WORK°WORK–temporarylibrarySASUSER°SASUSER–permanentlibraryYoucancreateandaccessyourownPROG2permanentlibraries.°PROG2–permanentlibrary82SASDataLibrariesThephysicalstructureofaSASdatalibrarydependsonyouroperatingsystem.Directory-basedoperatingsystems(WindowsorUNIX)¢anyfolderorsub-directoryz/OS(OS/390)systems¢speciallyformattedsequentialfile83 1.5WorkingwithExistingSASDataSets1-45TheLIBNAMEStatementTheLIBNAMEstatementestablishesthelibraryreference(orlibref),whichisanaliasfortheSASdatalibrary.GeneralformoftheLIBNAMEstatement:LIBNAMELIBNAMElibreflibref'SAS-data-library'SAS-data-library'';;Thelibrefmustbeeightcharactersorfewer.84Exceptfortheeight-characterlengthlimit,thelibraryreferencefollowsthenamingconventionsforSASdatasetsandvariables.Specifically,itmust•beginwithaletterorunderscore•includenospecialcharactersotherthantheunderscore.TheLIBNAMEStatement:ExamplesWindowslibnameprog2'c:prog2';UNIXlibnameprog2'/user/prog2';z/OS(OS/390)BatchandTSOlibnameprog2'edu.prog2.sasdata'disp=shr;85 1-46Chapter1IntroductionTwo-LevelSASDataSetNameslibref.SAS-filenamelibref.SAS-filenameSASDataSASLibrefDataLibrary86TheWORKLibraryTheWORKlibraryisthedefaultlibrary.IfyoudonotspecifyalibraryreferenceonaSASdatasetname,SASassumesthelibrefiswork.work.fltat1fltat187 1.5WorkingwithExistingSASDataSets1-47AccessingaPermanentSASDataSetTherearetwostepstoaccessingapermanentSASdataset:1.UseaLIBNAMEstatementtosetupalibrefthatpointstothelocationofthedataset.2.Referencethedatasetusingthelibrefasthefirstpartofthedatasetname.IfthelibrefisalreadyassignedintheSASsession,youdonotneedtoassignitagain.88 1-48Chapter1IntroductionViewingaPermanentSASDataSetWindowslibnameprog2'c:workshopwinsasprog2';procprintdata=prog2.testnoobs;run;89!ExceptforthenameoftheSASdatalibrary,theSAScodedoesnotchangeacrossoperatingsystems.ViewingaPermanentSASDataSetLNameScoreSMITH0.90JONES0.57MOORE0.85LEE0.98LONG0.67GREEN0.70FOREMAN0.6990 1.5WorkingwithExistingSASDataSets1-49ViewingaPermanentSASDataSetUNIXlibnameprog2'/users/prog2';procprintdata=prog2.testnoobs;run;91ViewingaPermanentSASDataSetLNameScoreSMITH0.90JONES0.57MOORE0.85LEE0.98LONG0.67GREEN0.70FOREMAN0.6992 1-50Chapter1IntroductionViewingaPermanentSASDataSetz/OS(OS/390)libnameprog2'.prog2.sasdata';procprintdata=prog2.testnoobs;run;931Theperiodatthebeginningofthez/OSfilenameconcatenatestheuserIDtothefront.ViewingaPermanentSASDataSetLNameScoreSMITH0.90JONES0.57MOORE0.85LEE0.98LONG0.67GREEN0.70FOREMAN0.69941Anyreferencetoz/OSappliestoOS/390,unlessotherwisenoted. 1.5WorkingwithExistingSASDataSets1-51CreatingaPermanentSASDataSetTherearetwostepswhenyoucreateapermanentSASdataset:1.UseaLIBNAMEstatementtosetupalibrefthatpointstothelocationyouwanttosaveto.2.UsethelibrefasthefirstleveloftheSASdatasetname.IfthelibrefisalreadyassignedintheSASsession,youdonotneedtoassignitagain.95CreatingaPermanentSASDataSetWindowslibnameprog2'c:workshopwinsasprog2';dataprog2.fltat1;infile'fltat1.dat';input@1EmpID$5.@7HireDatedate9.@17Salary5.;Bonus=.05*Salary;run;c01s5d1.sas96 1-52Chapter1IntroductionCreatingaPermanentSASDataSetUNIXlibnameprog2'/users/prog2';dataprog2.fltat1;infile'fltat1.dat';input@1EmpID$5.@7HireDatedate9.@17Salary5.;Bonus=.05*Salary;run;97CreatingaPermanentSASDataSetz/OS(OS/390)libnameprog2'.prog2.sasdata';dataprog2.fltat1;infile'.prog2.rawdata(fltat1)';input@1EmpID$5.@7HireDatedate9.@17Salary5.;Bonus=.05*Salary;run;98 1.5WorkingwithExistingSASDataSets1-53CreateaSASDataSetwithSASDataThescoresfromafinalexamLNameScorearestoredintheSASdatasetprog2.test.TheSMITH0.90professormustassigneachJONES0.57studentapassinggradeifMOORE0.85thescoreis0.7oraboveandLEE0.98afailinggradeotherwise.LONG0.67ThevariableScoreshouldGREEN0.70FOREMAN0.69notappearintheoutputdataset.99DesiredOutputThedatasetwork.fnlgradesshouldcontainonlythevariablesLNameandGrade.LNameGradeSMITHPassJONESFailedMOOREPassLEEPassLONGFailedGREENPassFOREMANFailed100 1-54Chapter1IntroductionTheSETStatementUseaSETstatementtoreadaSASdataset.GeneralformofaSETstatement:SETSETSAS-data-setSAS-data-set;;TheSETstatementpointstotheSASdataset(s)toberead.OptionsintheSETstatementaffecthowthedataisread.101IF-THENELSEStatementsOnemethodusedtoassignvaluesorexecutestatementsconditionallyisIF-THENELSEstatements.IFIFconditionconditionTHENTHENstatementstatement;;<;>……<;>102 1.5WorkingwithExistingSASDataSets1-55TheLENGTHStatementWhenyoucreatecharactervariableswithconditionallogicorfunctions,itisusuallyagoodideatoassignthelengthsexplicitlyusingaLENGTHstatement.GeneralformofaLENGTHstatement:LENGTHLENGTHvariable-namevariable-name<$><$>length-specification...length-specification...;;103SASsetsthetypeandlengththefirsttimethatavariableisreferencedintheprogram.AfterSASsetsthem,theattributescannotbechangedduringtheDATAstep.WhenyouuseaLENGTHstatement,becertainthatitisthefirststatementtoreferencethevariable. 1-56Chapter1IntroductionTheDROPStatementTodropvariablesthatarereadorcreatedduringtheDATAstep,useaDROPstatement.GeneralformofaDROPstatement:DROPDROPSAS-variable(s)SAS-variable(s);;VariablesdroppedwithaDROPstatementarereadintothePDVbutarenotoutputtothenewSASdataset.TheyareavailableforprocessingduringtheDATAstep.104AKEEPstatementisalsovalidforselectingvariablestooutputtoaSASdataset:KEEPSAS-variable(s);CreatingaVariablewithConditionalLogicdatafnlgrades;lengthGrade$6;dropScore;setprog2.test;ifScore>=.7thenGrade='Pass';elseGrade='Failed';run;105 1.5WorkingwithExistingSASDataSets1-57CompilingtheDATAStepdatafnlgrades;lengthGrade$6;dropScore;setprog2.test;ifScore>=.7thenGrade='Pass';elseGrade='Failed';run;PDVGrade$6106...CompilingtheDATAStepdatafnlgrades;lengthGrade$6;dropScore;setprog2.test;ifScore>=.7thenGrade='Pass';elseGrade='Failed';run;PDVGradeLNameScore$6$8N8107... 1-58Chapter1IntroductionCompilingtheDATAStepdatafnlgrades;lengthGrade$6;dropScore;setprog2.test;ifScore>=.7thenGrade='Pass';elseGrade='Failed';run;PDVGradeLNameScore$6$8DN8108...CompilingtheDATAStepdatafnlgrades;lengthGrade$6;dropScore;setprog2.test;ifScore>=.7thenGrade='Pass';elseGrade='Failed';run;PDVGradeLNameScore$6$8DN8fnlgradesdescriptorportionGradeLName$6$8109... 1.5WorkingwithExistingSASDataSets1-59ExecutingtheDATAStepprog2.growthdatafnlgrades;LNameScorelengthGrade$6;SMITH0.90dropScore;JONES0.57setprog2.test;MOORE0.85ifScore>=.7thenGrade='Pass';LEE0.98elseGrade='Failed';run;InitializePDVtomissingPDVGradeLNameScore$6$8DN80.90110...ExecutingtheDATAStepprog2.growthdatafnlgrades;LNameScorelengthGrade$6;SMITH0.90dropScore;JONES0.57setprog2.test;MOORE0.85ifScore>=.7thenGrade='Pass';LEE0.98elseGrade='Failed';run;PDVGradeLNameScore$6$8DN8SMITH0.90111... 1-60Chapter1IntroductionExecutingtheDATAStepprog2.growthdatafnlgrades;LNameScorelengthGrade$6;SMITH0.90dropScore;JONES0.57Truesetprog2.test;MOORE0.85ifScore>=.7thenGrade='Pass';LEE0.98elseGrade='Failed';run;PDVGradeLNameScore$6$8DN8SMITH0.90112...ExecutingtheDATAStepprog2.growthdatafnlgrades;LNameScorelengthGrade$6;SMITH0.90dropScore;JONES0.57setprog2.test;MOORE0.85ifScore>=.7thenGrade='Pass';LEE0.98elseGrade='Failed';run;PDVGradeLNameScore$6$8DN8PassSMITH0.90113... 1.5WorkingwithExistingSASDataSets1-61ExecutingtheDATAStepprog2.growthdatafnlgrades;LNameScorelengthGrade$6;SMITH0.90dropScore;JONES0.57setprog2.test;MOORE0.85ifScore>=.7thenGrade='Pass';LEE0.98elseGrade='Failed';run;PDVAutomaticGradeLNameScoreoutput$6$8DN8PassSMITH0.90fnlgradesGradeLNamePassSMITH114...ExecutingtheDATAStepprog2.growthdatafnlgrades;LNameScorelengthGrade$6;SMITH0.90dropScore;JONES0.57setprog2.test;MOORE0.85ifScore>=.7thenGrade='Pass';LEE0.98elseGrade='Failed';run;PDVAutomaticreturnGradeLNameScore$6$8DN8PassSMITH0.90fnlgradesGradeLNamePassSMITH115... 1-62Chapter1IntroductionExecutingtheDATAStepprog2.growthdatafnlgrades;LNameScorelengthGrade$6;SMITH0.90dropScore;JONES0.57setprog2.test;MOORE0.85ReinitializePDV.ValuesofifScore>=.7thenGrade='Pass';LEE0.98variablesnotreadfromelseGrade='Failed';run;SASaresettomissing.PDVGradeLNameScore$6$8DN8SMITH0.90fnlgradesGradeLNamePassSMITH116...ExecutingtheDATAStepprog2.growthdatafnlgrades;LNameScorelengthGrade$6;SMITH0.90dropScore;JONES0.57setprog2.test;MOORE0.85ifScore>=.7thenGrade='Pass';LEE0.98elseGrade='Failed';run;PDVGradeLNameScore$6$8DN8JONES0.57fnlgradesGradeLNamePassSMITH117... 1.5WorkingwithExistingSASDataSets1-63ExecutingtheDATAStepprog2.growthdatafnlgrades;LNameScorelengthGrade$6;SMITH0.90dropScore;JONES0.57setprog2.test;FalseMOORE0.85ifScore>=.7thenGrade='Pass';LEE0.98elseGrade='Failed';run;PDVGradeLNameScore$6$8DN8JONES0.57fnlgradesGradeLNamePassSMITH118...ExecutingtheDATAStepprog2.growthdatafnlgrades;LNameScorelengthGrade$6;SMITH0.90dropScore;JONES0.57setprog2.test;MOORE0.85ifScore>=.7thenGrade='Pass';LEE0.98elseGrade='Failed';run;PDVGradeLNameScore$6$8DN8FailedJONES0.57fnlgradesGradeLNamePassSMITH119... 1-64Chapter1IntroductionExecutingtheDATAStepprog2.growthdatafnlgrades;LNameScorelengthGrade$6;SMITH0.90dropScore;JONES0.57setprog2.test;MOORE0.85ifScore>=.7thenGrade='Pass';LEE0.98elseGrade='Failed';run;PDVAutomaticGradeLNameScoreoutput$6$8DN8FailedJONES0.57fnlgradesGradeLNamePassSMITH120FailedJONES...ExecutingtheDATAStepprog2.growthdatafnlgrades;LNameScorelengthGrade$6;SMITH0.90dropScore;JONES0.57setprog2.test;MOORE0.85ifScore>=.7thenGrade='Pass';LEE0.98elseGrade='Failed';run;PDVAutomaticGradeLNameScorereturn$6$8DN8FailedJONES0.57fnlgradesGradeLNamePassSMITH121FailedJONES... 1.5WorkingwithExistingSASDataSets1-65ExecutingtheDATAStepprog2.growthdatafnlgrades;LNameScorelengthGrade$6;SMITH0.90dropScore;ContinueprocessingJONES0.57setprog2.test;MOORE0.85untilendoffileifScore>=.7thenGrade='Pass';LEE0.98elseGrade='Failed';run;PDVGradeLNameScore$6$8DN8FailedJONES0.57fnlgradesGradeLNamePassSMITH122FailedJONESCreatingaVariablewithConditionalLogicprocprintdata=fnlgradesnoobs;run;GradeLNamePassSMITHFailedJONESPassMOOREPassLEEFailedLONGPassGREENFailedFOREMAN123 1-66Chapter1IntroductionUsingtheVARStatementprocprintdata=fnlgradesnoobs;varLNameGrade;run;LNameGradeSMITHPassJONESFailedMOOREPassLEEPassLONGFailedGREENPassFOREMANFailedc01s5d2.sas124 1.6PrerequisiteSyntax(Self-Study)1-671.6PrerequisiteSyntax(Self-Study)Thefollowingisasyntaxguidetostatementsandproceduresyoushouldknowbeforeyoustartthisclass.StatementsValidOnlyinaDATAStepTostarttheDATAstepandnamethedatasetbeingcreated:DATASAS-dataset;Tousearawdatafileasinput:INFILE'raw-data-file';andINPUTvariable-specifications;TouseaSASdatasetasinput:SETSAS-data-set;Tocreateanewvariable(assignmentstatement):variable-name=expression;Toperformconditionalprocessing:IFconditionTHENstatement;…DATAStepCompile-Time-OnlyStatementsToexplicitlysetthelengthofavariable:LENGTHvariable-name<$>length-specification...;Todropavariableorvariablesonoutput:DROPSASvariable(s)tobedropped;orKEEPSASvariable(s)tobekept; 1-68Chapter1IntroductionProceduresTodisplaythedescriptorportionofaSASdataset:PROCCONTENTSDATA=SAS-data-set;RUN;TocreatealistreportofaSASdataset:PROCPRINTDATA=SAS-data-set;RUN;TocontrolwhichvariablesareshowninthePROCPRINTandtheirorder:VARSAS-variable(s);StatementsValidinaProcedureorDATAStepToapplyaformattoavariableorvariables:FORMATvariable-nameformat.…;Generalformofaformatname:<$>FORMAT-NAMEw.;where$indicatesacharacterformat.FORMAT-NAMEisthenameoftheformat.wspecifiesthetotalcharactersavailablefordisplayingthevalue..istherequireddelimiter.dspecifiesthenumberofdecimalplacestobedisplayedforanumericvalue.CommonNumericFormatsCOMMAw.daddscommastothevalue.DOLLARw.daddsdollarsignsandcommastothevalue.MMDDYY10.displaysSASdatesintheform12/31/2012.DATE9.displaysSASdatesintheform31DEC2012. 1.6PrerequisiteSyntax(Self-Study)1-69GlobalStatementsToassignalibraryreferencetoaSASdatalibrary:LIBNAMElibref'operating-system-location';ToassignaheadertoSASoutput:TITLEn'header';Youcanspecifyuptotentitles.TITLEisequivalenttoTITLE1.!Whenatitleisset,itstaysineffectuntilitischangedorcanceled,oruntiltheSASsessionends. 1-70Chapter1Introduction1.7NavigatingtheSASWindowingEnvironment(Self-Study)TheseinstructionsareintendedforstudentsnavigatingtheSASwindowingenvironmentonSASclassroommachines.Theymightnotbeappropriateforallsites.NavigatingtheSASWindowingEnvironmentonWindowsTheEnhancedEditor(thedefaulteditoronWindows)isonlyavailableontheWindowsoperatingsystem.UnliketheProgramEditor,itdoesnotautomaticallyclearwhencodeissubmitted,andyoucanhavemultipleEnhancedEditorwindowsopensimultaneously.YoucanusetheProgramEditor(thedefaulteditorinSASVersion6andearlier)byselectingViewÖProgramEditor.NavigatingtheWindowsTonavigatetoanywindow,dooneofthefollowing:•Selectthewindowbuttonatthebottomofthescreen(ifthewindowisopen).•SelectthewindownamefromtheViewdrop-downmenu.•TypethenameofthewindowinthecommandbarandpresstheENTERkey.Tocloseanywindow,dooneofthefollowing:•Selectintheupper-rightcornerofthewindow.•Typeendinthecommandbar,andpresstheENTERkey. 1.7NavigatingtheSASWindowingEnvironment(Self-Study)1-71OpeningaSASProgramToopenaSASprogram,theProgramEditorortheEnhancedEditormustbetheactivewindow.1.SelectFileÖOpenorselect.AWindowsdialogboxappears.2.Navigatethroughthefoldersandhighlighttheprogram.3.SelectOK.SubmittingaSASProgramTosubmitaprogram,theProgramEditorortheEnhancedEditormustbetheactivewindow,andthecodetobesubmittedmustbeinthewindow.1.Highlightthecodeyouwanttosubmit.(Thisisnotnecessaryifyousubmittheentirecontentsofthewindow.)2.IssuetheSUBMITcommandbyselecting,pressingtheF3key,orselectingRunÖSubmit.RecallingSubmittedCodeTheProgramEditorisclearedautomaticallyeverytimecodeissubmittedfromit.Torecallsubmittedcode,maketheProgramEditortheactivewindow,anddooneofthefollowing:•SelectRunÖRecall.•Typerecallinthecommandbar,andpresstheENTERkey.•UsetheF4shortcutkey.!TheRECALLcommandcanalsobeusedfromtheEnhancedEditortoretrievelostcodethatwassubmitted.SavingaSASProgramTosaveaSASprogram,theProgramEditorortheEnhancedEditormustbetheactivewindow,andthecodeyouwanttosavemustbeinthewindow.1.SelectFileÖSaveAs....AWindowsdialogboxappears.2.Navigatetothefolderinwhichyouwanttosavetheprogram.3.Typeanamefortheprogramintheappropriatebox.4.SelectOK.ClearingWindowsToclearawindow,dooneofthefollowing:•Activatethewindow,typeclearinthecommandbar,andpresstheENTERkey.•ActivatethewindowandselectEditÖClearAll.•TypeclearandthenameofthewindowinthecommandbarandpresstheENTERkey. 1-72Chapter1IntroductionIssuingMultipleCommandsatOnceToissuemorethanonecommandatthesametime,typethecommandsinthecommandbarseparatedbysemicolons.Forexample,toclearboththeLogandOutputwindows,typethefollowinginthecommandbar:clearlog;clearoutputNavigatingtheSASWindowingEnvironmentonUNIXIntheUNIXenvironment,SASwindowsarefloating,notdocked.Thereisafloatingtoolbarwithacommandbarandshortcuticons.Drop-downmenusareatthetopofeachwindow.NavigatingtheWindowsToactivateanywindow,dooneofthefollowing:•Selectthewindowiconatthebottomofthescreen.•SelectthewindownamefromtheViewdrop-downmenu.•Typethewindownameinthecommandbar,andpresstheENTERkey. 1.7NavigatingtheSASWindowingEnvironment(Self-Study)1-73SubmittingaProgramTosubmitaSASprogram,theProgramEditormustbetheactivewindowandcontainthecodeyouwanttosubmit.DoanyofthefollowingtosubmitthecontentsoftheProgramEditor:•Typesubmitinthecommandbar,andpresstheENTERkey.•UsetheF3shortcutkey.•Selectfromthetoolbar.•SelectRunÖSubmit.RecallingSubmittedCodeTheProgramEditorisclearedautomaticallyeverytimecodeissubmittedfromit.Torecallsubmittedcode,maketheProgramEditortheactivewindow,anddooneofthefollowing:•SelectRunÖRecall.•Typerecallinthecommandbar,andpresstheENTERkey.•UsetheF4shortcutkey.SavingaSASProgramTosaveaSASprogram,theProgramEditormustbetheactivewindow,andthecodeyouwanttosavemustbeinthewindow.1.SelectFileÖSaveAs....Adialogboxappears.2.Navigatetothedirectoryinwhichyouwanttosavetheprogram.3.Typeanamefortheprogramintheappropriatebox.4.SelectOK.ClearingWindowsToclearawindow,dooneofthefollowing:•Activatethewindow,typeclearinthecommandbar,andpresstheENTERkey.•ActivatethewindowandselectEditÖClearAll.•Typeclearandthenameofthewindowatthecommandbar,andpresstheENTERkey.IssuingMultipleCommandsatOnceTosubmitmorethanonecommandatthesametime,typethecommands,separatedbysemicolons,inthecommandbarandpresstheENTERkey.Forexample,toclearboththeLogandOutputwindows,typethefollowinginthecommandbar:clearlog;clearoutput 1-74Chapter1IntroductionNavigatingtheSASWindowingEnvironmentonz/OSEachtimeyoulogon,1.opentheOutputwindowbytypingoutputonanycommandlineandpressingtheENTERkey.2.issuethefollowingcommandfromthecommandlineoftheOutputwindow.(Thispreventssuspendedoutput.)autoscroll0NavigatingtheWindows•Eachwindowcontainsacommandline.•YoucanopenanywindowbytypingitsnameonanycommandlineandpressingtheENTERkey.•ThePageUpandPageDownkeysonyourkeyboardmovefromoneopenwindowtoanother.•F7andF8enableyoutoscrollupanddownwithinawindow.•TocloseanywindowandreturntotheProgramEditor,issuetheENDcommandorusetheF3key.IftheProgramEditorisactive,theF3keysubmitsthecodeinthewindow.•Tomaximizeawindow,typeZonthecommandlineandpresstheENTERkey.Torestorethewindowtonormalsize,typeZonthecommandlineofthemaximizedwindowandpresstheENTERkey.IncludingaSASProgramToincludeaSASprograminyoursession,theProgramEditormustbetheactivewindow.1.Typeinclude'name-of-SAS-program'onthecommandlineoftheProgramEditorwindow.2.PresstheENTERkey.SubmittingaProgramTosubmitaSASprogram,theProgramEditormustbetheactivewindowandcontainthecodeyouwanttosubmit.Tosubmitcode,dooneofthefollowing:•TypesubmitinthecommandlineoftheProgramEditor,andpresstheENTERkey.•UsetheF3shortcutkey.RecallingSubmittedCodeTheProgramEditorisclearedautomaticallyeverytimecodeissubmittedfromit.Torecallsubmittedcode,maketheProgramEditortheactivewindowanddooneofthefollowing:•TyperecallinthecommandlineoftheProgramEditor,andpresstheENTERkey.•UsetheF4shortcutkey.SavingaSASProgramTosaveaSASprogram,theProgramEditormustbetheactivewindowandcontainthecodeyouwanttosave.1.Typefile'name-of-SAS-program'onthecommandlineoftheProgramEditorwindow.2.PresstheENTERkey.Anoteappearsatthetopofthewindow. 1.7NavigatingtheSASWindowingEnvironment(Self-Study)1-75ClearingWindowsToclearawindow,dooneofthefollowing:•TypeclearonthecommandlineofthatwindowandpresstheENTERkey.•TypeclearandthenameofthewindowtobeclearedonanycommandlineandpresstheENTERkey.EditingSASProgramCodeintheUNIXandz/OSEnvironmentsProgramEditorLineNumberCommandsMostWindowsusersutilizecopyandpastecommands.However,theProgramEditorinallthreeenvironmentsallowstheuseoflinenumbercommands.Usethesecommandstocopy,paste,ordeleteprogramcode.Iinsertsoneline(after)thecurrentline.Ininsertsnlines(after)thecurrentline.IBinsertsoneline(before)thecurrentline.IBninsertsnlines(before)thecurrentline.Ddeletesthecurrentline.Dndeletesnlines.DDdeletesablockoflines.Typeddonthefirstandlastlinesoftheblock.Rrepeatsthecurrentlineonce.Rnrepeatsthecurrentlinentimes.RRrepeatsablockoflinesonce.Typerronthefirstandlastlinesoftheblock.MovingandCopyingCodeTocopyormoveonelineofcode,dothefollowing:1.Typec(tocopy)orm(tomove)thelineyouwanttocopyormove.2.Typea(forafter)orb(forbefore)ontheappropriatelinetoindicatewhereyouwanttocopyormovethespecifiedline.Tocopyormoveablockoflinesofcode,dothefollowing:1.Typeccormmonthefirstlineyouwanttocopyormove.2.Typeccormmonthelastlineyouwanttocopyormove.3.Typea(forafter)orb(forbefore)ontheappropriatelinetoindicatewhereyouwanttocopyormovetheblockoflines.!LinenumbercommandsarenotavailableintheWindowsEnhancedEditor. 1-76Chapter1Introduction Chapter2ControllingInputandOutput2.1OutputtingMultipleObservations.................................................................................2-32.2WritingtoMultipleSASDataSets...............................................................................2-202.3SelectingVariablesandObservations.......................................................................2-272.4WritingtoanExternalFile...........................................................................................2-452.5SolutionstoExercises.................................................................................................2-68 2-2Chapter2ControllingInputandOutput 2.1OutputtingMultipleObservations2-32.1OutputtingMultipleObservationsObjectives¢ExplicitlycontroltheoutputofmultipleobservationstoaSASdataset.3AForecastingApplicationThegrowthrateofeachdivisionofanairlineisforecastinprog2.growth.Ifeachofthefivedivisionsgrowsatitsrespectiverateforthenextthreeyears,whatwillbetheapproximatesizeofeachdivisionattheendofeachofthethreeyears?PartialListingofprog2.growthNumDivisionEmpsIncreaseAPTOPS2050.075FINACE1980.040FLTOPS1870.0804 2-4Chapter2ControllingInputandOutputAForecastingApplicationTheoutputSASdataset,forecast,shouldcontain15observations.PartialListingofforecastNewDivisionIncreaseYearTotalAPTOPS0.0751220.38APTOPS0.0752236.90APTOPS0.0753254.67FINACE0.0401205.92FINACE0.0402214.165AutomaticOutput(Review)Bydefault,everyDATAstepcontainsanautomaticOUTPUTstatementattheendofeachiteration.ThisautomaticOUTPUTstatementtellstheSASSystemtowriteobservationstothedatasetordatasetsthatarecreated.dataforecast;setprog2.growth;2.Automatic;run;1.Automaticoutput6 2.1OutputtingMultipleObservations2-5TheOUTPUTStatementTheexplicitOUTPUTstatementwritesthecurrentcontentsofthePDVtoaSASdataset.PlacinganexplicitOUTPUTstatementinaDATAstepoverridestheautomaticoutput,andSASaddsanobservationtoadatasetonlywhenanexplicitOUTPUTstatementisexecuted.OUTPUTOUTPUT;>;7UsinganexplicitOUTPUTstatementwithoutargumentscausesthecurrentobservationtobewrittentoalldatasetsthatarenamedintheDATAstatement.!ImplicitreturntothebeginningoftheDATAstepoccursafterthebottomofthestepisreached;notwhenanexplicitOUTPUTstatementisexecuted. 2-6Chapter2ControllingInputandOutputAForecastingApplicationdataforecast;dropNumEmps;setprog2.growth;Year=1;NewTotal=NumEmps*(1+Increase);output;Year=2;NewTotal=NewTotal*(1+Increase);output;Year=3;NewTotal=NewTotal*(1+Increase);output;run;c02s1d1.sas8Inyearstwoandthree,theexistingvalueofNewTotalisusedtocalculatethenewvalueofNewTotal.ExplicitOutput:Compilationdataforecast;dropNumEmps;setprog2.growth;Year=1;NewTotal=NumEmps*(1+Increase);output;Year=2;NewTotal=NewTotal*(1+Increase);output;Year=3;NewTotal=NewTotal*(1+Increase);output;run;PDVDivisionNumEmpsIncrease$6N8N89... 2.1OutputtingMultipleObservations2-7ExplicitOutput:Compilationdataforecast;dropNumEmps;setprog2.growth;Year=1;NewTotal=NumEmps*(1+Increase);output;Year=2;NewTotal=NewTotal*(1+Increase);output;Year=3;NewTotal=NewTotal*(1+Increase);output;PDVrun;DivisionNumEmpsIncreaseYear$6N8N8N810...ExplicitOutput:Compilationdataforecast;dropNumEmps;setprog2.growth;Year=1;NewTotal=NumEmps*(1+Increase);output;Year=2;NewTotal=NewTotal*(1+Increase);output;Year=3;NewTotal=NewTotal*(1+Increase);output;PDVrun;DivisionNumEmpsIncreaseYearNewTotal$6N8N8N8N811... 2-8Chapter2ControllingInputandOutputExplicitOutput:Compilationdataforecast;dropNumEmps;setprog2.growth;Year=1;NewTotal=NumEmps*(1+Increase);output;Year=2;NewTotal=NewTotal*(1+Increase);output;Year=3;NewTotal=NewTotal*(1+Increase);output;PDVrun;DivisionNumEmpsIncreaseYearNewTotal$6DN8N8N8N812...ExplicitOutput:Executiondataforecast;dropNumEmps;prog2.growthsetprog2.growth;NumYear=1;DivisionEmpsIncreaseNewTotal=NumEmps*(1+Increase);output;APTOPS2050.075Year=2;FINACE1980.040NewTotal=NewTotal*(1+Increase);FLTOPS1870.080output;Year=3;NewTotal=NewTotal*(1+Increase);InitializePDVtomissingoutput;run;PDVDivisionNumEmpsIncreaseYearNewTotal$6DN8N8N8N8....13... 2.1OutputtingMultipleObservations2-9ExplicitOutput:Executiondataforecast;dropNumEmps;prog2.growthsetprog2.growth;NumYear=1;DivisionEmpsIncreaseNewTotal=NumEmps*(1+Increase);output;APTOPS2050.075Year=2;FINACE1980.040NewTotal=NewTotal*(1+Increase);FLTOPS1870.080output;Year=3;NewTotal=NewTotal*(1+Increase);output;run;PDVDivisionNumEmpsIncreaseYearNewTotal$6DN8N8N8N8APTOPS2050.075..14...ExplicitOutput:Executiondataforecast;dropNumEmps;prog2.growthsetprog2.growth;NumYear=1;DivisionEmpsIncreaseNewTotal=NumEmps*(1+Increase);output;APTOPS2050.075Year=2;FINACE1980.040NewTotal=NewTotal*(1+Increase);FLTOPS1870.080output;Year=3;NewTotal=NewTotal*(1+Increase);output;run;PDVDivisionNumEmpsIncreaseYearNewTotal$6DN8N8N8N8APTOPS2050.0751.15... 2-10Chapter2ControllingInputandOutputExplicitOutput:Executiondataforecast;dropNumEmps;prog2.growthsetprog2.growth;NumYear=1;DivisionEmpsIncreaseNewTotal=NumEmps*(1+Increase);output;APTOPS2050.075Year=2;FINACE1980.040NewTotal=NewTotal*(1+Increase);FLTOPS1870.080output;Year=3;NewTotal=NewTotal*(1+Increase);output;run;205*(1+0.075)PDVDivisionNumEmpsIncreaseYearNewTotal$6DN8N8N8N8APTOPS2050.0751220.3816...ExplicitOutput:Executiondataforecast;dropNumEmps;prog2.growthsetprog2.growth;NumYear=1;DivisionEmpsIncreaseNewTotal=NumEmps*(1+Increase);output;APTOPS2050.075Year=2;FINACE1980.040NewTotal=NewTotal*(1+Increase);FLTOPS1870.080output;Year=3;NewTotal=NewTotal*(1+Increase);output;run;PDVDivisionNumEmpsIncreaseYearNewTotal$6DN8N8N8N8APTOPS2050.0751220.38Writefirstobservationtoforecast.17... 2.1OutputtingMultipleObservations2-11ExplicitOutput:Executiondataforecast;dropNumEmps;prog2.growthsetprog2.growth;NumYear=1;DivisionEmpsIncreaseNewTotal=NumEmps*(1+Increase);output;APTOPS2050.075Year=2;FINACE1980.040NewTotal=NewTotal*(1+Increase);FLTOPS1870.080output;Year=3;NewTotal=NewTotal*(1+Increase);output;run;PDVDivisionNumEmpsIncreaseYearNewTotal$6DN8N8N8N8APTOPS2050.0752220.3818...ExplicitOutput:Executiondataforecast;dropNumEmps;prog2.growthsetprog2.growth;NumYear=1;DivisionEmpsIncreaseNewTotal=NumEmps*(1+Increase);output;APTOPS2050.075Year=2;FINACE1980.040NewTotal=NewTotal*(1+Increase);FLTOPS1870.080output;Year=3;NewTotal=NewTotal*(1+Increase);output;run;220.38*(1+0.075)PDVDivisionNumEmpsIncreaseYearNewTotal$6DN8N8N8N8APTOPS2050.0752236.9019... 2-12Chapter2ControllingInputandOutputExplicitOutput:Executiondataforecast;dropNumEmps;prog2.growthsetprog2.growth;NumYear=1;DivisionEmpsIncreaseNewTotal=NumEmps*(1+Increase);output;APTOPS2050.075Year=2;FINACE1980.040NewTotal=NewTotal*(1+Increase);FLTOPS1870.080output;Year=3;NewTotal=NewTotal*(1+Increase);output;run;PDVDivisionNumEmpsIncreaseYearNewTotal$6DN8N8N8N8APTOPS2050.0752236.9020Writesecondobservationtoforecast....ExplicitOutput:Executiondataforecast;dropNumEmps;prog2.growthsetprog2.growth;NumYear=1;DivisionEmpsIncreaseNewTotal=NumEmps*(1+Increase);output;APTOPS2050.075Year=2;FINACE1980.040NewTotal=NewTotal*(1+Increase);FLTOPS1870.080output;Year=3;NewTotal=NewTotal*(1+Increase);output;run;PDVDivisionNumEmpsIncreaseYearNewTotal$6DN8N8N8N8APTOPS2050.0753236.9021... 2.1OutputtingMultipleObservations2-13ExplicitOutput:Executiondataforecast;dropNumEmps;prog2.growthsetprog2.growth;NumYear=1;DivisionEmpsIncreaseNewTotal=NumEmps*(1+Increase);output;APTOPS2050.075Year=2;FINACE1980.040NewTotal=NewTotal*(1+Increase);FLTOPS1870.080output;Year=3;NewTotal=NewTotal*(1+Increase);output;run;236.90*(1+0.075)PDVDivisionNumEmpsIncreaseYearNewTotal$6DN8N8N8N8APTOPS2050.0753254.6722...ExplicitOutput:Executiondataforecast;dropNumEmps;prog2.growthsetprog2.growth;NumYear=1;DivisionEmpsIncreaseNewTotal=NumEmps*(1+Increase);output;APTOPS2050.075Year=2;FINACE1980.040NewTotal=NewTotal*(1+Increase);FLTOPS1870.080output;Year=3;NewTotal=NewTotal*(1+Increase);output;run;PDVDivisionNumEmpsIncreaseYearNewTotal$6DN8N8N8N8APTOPS2050.0753254.6723Writethirdobservationtoforecast.... 2-14Chapter2ControllingInputandOutputExplicitOutput:Executiondataforecast;dropNumEmps;prog2.growthsetprog2.growth;NumYear=1;DivisionEmpsIncreaseNewTotal=NumEmps*(1+Increase);output;APTOPS2050.075Year=2;FINACE1980.040NewTotal=NewTotal*(1+Increase);FLTOPS1870.080output;Year=3;NewTotal=NewTotal*(1+Increase);output;run;PDVNoautomaticDivisionNumEmpsIncreaseYearNewTotaloutput$6DN8N8N8N8APTOPS2050.0753254.6724...ExplicitOutput:Executiondataforecast;dropNumEmps;prog2.growthsetprog2.growth;NumYear=1;DivisionEmpsIncreaseNewTotal=NumEmps*(1+Increase);output;APTOPS2050.075Year=2;FINACE1980.040NewTotal=NewTotal*(1+Increase);FLTOPS1870.080output;Year=3;NewTotal=NewTotal*(1+Increase);output;run;PDVAutomaticreturnDivisionNumEmpsIncreaseYearNewTotal$6DN8N8N8N8APTOPS2050.0753254.6725 2.1OutputtingMultipleObservations2-15ExplicitOutput:ExecutionContentsoftheFORECASTdatasetafterthefirstexecutionoftheDATAstep:DivisionIncreaseYearNewTotalAPTOPS0.0751220.38APTOPS0.0752236.90APTOPS0.0753254.6726ExplicitOutput:Executiondataforecast;dropNumEmps;prog2.growthsetprog2.growth;NumYear=1;DivisionEmpsIncreaseNewTotal=NumEmps*(1+Increase);output;APTOPS2050.075Year=2;FINACE1980.040NewTotal=NewTotal*(1+Increase);FLTOPS1870.080output;Year=3;NewTotal=NewTotal*(1+Increase);ReinitializePDVtomissingoutput;run;PDVDivisionNumEmpsIncreaseYearNewTotal$6DN8N8N8N8APTOPS2050.075..27... 2-16Chapter2ControllingInputandOutputExplicitOutput:Executiondataforecast;dropNumEmps;prog2.growthsetprog2.growth;NumYear=1;DivisionEmpsIncreaseNewTotal=NumEmps*(1+Increase);output;APTOPS2050.075Year=2;FINACE1980.040NewTotal=NewTotal*(1+Increase);FLTOPS1870.080output;Year=3;ContinueexecutingDATANewTotal=NewTotal*(1+Increase);output;stepuntilallobservationsrun;PDVfromprog2.growthDivisionarereadNumEmpsIncreaseYearNewTotal$6DN8N8N8N8FINACE1980.040..28ExplicitlyControllingOutputPartialLogNOTE:Therewere5observationsreadfromthedatasetPROG2.GROWTH.NOTE:ThedatasetWORK.FORECASThas15observationsand4variables.29 2.1OutputtingMultipleObservations2-17ExplicitlyControllingOutputprocprintdata=forecastnoobs;formatNewTotal6.;run;PartialPROCPRINTOutputNewDivisionIncreaseYearTotalAPTOPS0.0751220APTOPS0.0752237APTOPS0.0753255FINACE0.0401206FINACE0.040221430 2-18Chapter2ControllingInputandOutputExercisesTheseexercisesuseSASdatasetsstoredinapermanentSASdatalibrary.FillintheblankwiththelocationofyourSASdatalibrary.SubmittheLIBNAMEstatementtoassignthelibrefPROG2totheSASdatalibrary.libnameprog2'______________________________________';1.OutputtingMultipleObservationsRotating,ortransposing,aSASdatasetcanbeaccomplishedbyusingexplicitOUTPUTstatementsinaDATAstep.Whenadatasetisrotated,thevaluesofanobservationintheinputdatasetbecomevaluesofavariableintheoutputdataset.UseexplicitOUTPUTstatementstorotateprog2.donateintoadatasetcalledrotate.Createfouroutputobservationsinrotatefromeachinputobservationinprog2.donate.Therotatedatasetshouldhavethreevariables:ID,Qtr,andAmount.Printthedatasettoverifyyourresults.PartialListingofprog2.donateIDQtr1Qtr2Qtr3Qtr4E00224123322.E0036735484030E00441.638990E0058716193029E005984861PartialListingofrotateObsIDQtrAmount1E002241122E002242333E002243224E002244.5E003671356E003672487E003673408E003674309E004411.10E0044126311E0044138912E00441490 2.1OutputtingMultipleObservations2-192.UsingConditionalLogictoOutputMultipleObservations(Optional)Theprog2.ffmethoddatasetcontainsinformationaboutthedifferentwaysthatfrequentflyerspurchasedairlinetickets.AvalueofYintheInternet,Telephone,orTravelAgencyvariableindicatesthatthefrequentflyerusedthatmethod.prog2.ffmethodTravelIDInternetTelephoneAgencyF31351NYYF161YYNF212NNYF25122YNNUseexplicitOUTPUTstatementstocreateadatasetcalledbuyhistory.Thisdatasetwillcontainoneobservationforeachmethodusedbyeachfrequentflyer.TherewillbetwoobservationsinbuyhistorythatrefertoF31351,butonlyoneobservationthatreferstoF212.Thebuyhistorydatasetshouldhavetwovariables:IDandMethod.Printthedatasettoverifyyourresults.buyhistoryObsIDMethod1F31351Telephone2F31351TravelAgency3F161Internet4F161Telephone5F212TravelAgency6F25122Internet!ADOstatementcanbeusedwithinIF-THEN/ELSEstatementstodesignateagroupofstatementstobeexecuted,dependingonwhethertheIFconditionistrueorfalse. 2-20Chapter2ControllingInputandOutput2.2WritingtoMultipleSASDataSetsObjectives¢CreatemultipleSASdatasetsinasingleDATAstep.¢Useconditionalprocessingtocontrolthedataset(s)towhichanobservationiswritten.33WritingtoMultipleSASDataSetsThedatasetprog2.militarycontainsinformationaboutairfacilitiesmaintainedbytheArmy,Navy,AirForce,andMarines.CreatefourSASdatasets:airforce,army,navy,andmarines.Eachofthefourdatasetsshouldcontaininformationaboutasinglebranchofthearmedforces.34 2.2WritingtoMultipleSASDataSets2-21WritingtoMultipleSASDataSetsprocprintdata=prog2.militarynoobs;PROG2.MILITARY(Partialoutput.)varCodeType;run;PartialPROCPRINTOutputCodeTypeSKFAirForceDPGArmyHIFAirForceNFENavalDAAArmy35TheDATAStatementTheDATAstatementbeginsaDATAstepandprovidesnamesforanyoutputSASdatasets.YoucancreatemultipleSASdatasetsinasingleDATAstepbylistingthenamesoftheoutputdatasetsseparatedbyatleastonespace.DATADATA<<…><…data-set-name-ndata-set-name-n>>;;36IfyoudonotspecifyaSASdatasetnameorthereservedname_NULL_inaDATAstatement,thenSASautomaticallycreatesdatasetswiththenamesdata1,data2,andsoonintheworklibrarybydefault. 2-22Chapter2ControllingInputandOutputTheOUTPUTStatement(Review)Bydefault,theexplicitOUTPUTstatementwritesthecurrentobservationtoeverySASdatasetlistedintheDATAstatement.Youcanspecifythename(s)ofadatasetordatasetstowhichSASwritestheobservation.OUTPUTOUTPUT<…SAS-data-set-n<…SAS-data-set-n>>;;37SAS-data-set-1throughSAS-data-set-nmustalsoappearintheDATAstatement.!TospecifymultipledatasetsinasingleOUTPUTstatement,separatethedatasetnameswithaspace:outputdata1data2; 2.2WritingtoMultipleSASDataSets2-23WritingtoMultipleSASDataSetsdataairforcearmynavymarines;dropType;setprog2.military;ifTypeeq'AirForce'thenoutputairforce;elseifTypeeq'Army'thenoutputarmy;elseifTypeeq'Naval'thenoutputnavy;elseifTypeeq'Marine'thenoutputmarines;run;c02s2d1.sas38AnalternateformofconditionallyexecutingstatementsusesSELECTgroups.SELECT<(select-expression)>;WHEN-1(when-expression-1<…,when-expression-n>)statement;<…WHEN-n(when-expression-1<…,when-expression-n>)statement;>END;TheDATAstepshownabovecouldberewrittentouseSELECTgroupsasfollows:dataarmynavyairforcemarines;dropType;setprog2.military;select(Type);when('AirForce')outputairforce;when('Army')outputarmy;when('Naval')outputnavy;when('Marine')outputmarines;otherwise;end;run;SeeSASdocumentationformoreinformationaboutusingSELECTgroups. 2-24Chapter2ControllingInputandOutputWritingtoMultipleSASDataSetsPartialLogNOTE:Therewere137observationsreadfromthedatasetPROG2.MILITARY.NOTE:ThedatasetWORK.AIRFORCEhas64observationsand5variables.NOTE:ThedatasetWORK.ARMYhas41observationsand5variables.NOTE:ThedatasetWORK.NAVYhas28observationsand5variables.NOTE:ThedatasetWORK.MARINEShas4observationsand5variables.39 2.2WritingtoMultipleSASDataSets2-25Exercises3.WritingtoMultipleSASDataSetsThedatasetprog2.elementscontainsinformationabouttheknownelementsintheperiodictable.Eachobservationcontainsanelement’sname,symbol,atomicnumber,andstate.ThevalueofStatereferstowhethertheelementisagas,liquid,solid,orsyntheticatroomtemperature.!Asyntheticelementisanelementthatisnotpresentinnature.CreatefourSASdatasets:gas,liquid,solid,andsynthetic.Eachdatasetwillcontaininformationaboutthoseelementsthathavethatstateatroomtemperature.Eachofthesefourdatasetsshouldcontainthreevariables;theyshouldnotcontaintheStatevariable.!Charactervaluesarecase-sensitive.Thegasdatasetshouldcontain11observations.Theliquiddatasetshouldcontain4observations.Thesoliddatasetshouldcontain76observations.Thesyntheticdatasetshouldcontain24observations.PartialListingofprog2.elementsAtomicNameSymbolNumStateActiniumAc89SolidAluminumAl13SolidAmericiumAm95SyntheticAntimonySb51SolidArgonAr18GasArsenicAs33SolidAstatineAt85SolidBariumBa56SolidBerkeliumBk97SyntheticBerylliumBe4SolidBismuthBi83SolidBohriumBh107SolidBoronB5SolidBromineBr35Liquid 2-26Chapter2ControllingInputandOutputListingofliquidAtomicObsNameSymbolNum1BromineBr352CaesiumCs553FranciumFr874MercuryHg80!ThenamesofelementsandtheirsymbolsareapprovedbyIUPAC,theInternationalUnionofPureandAppliedChemistry.IUPAChasnotapprovednamesforelementswithatomicnumbersabove109;therefore,temporaryIUPACnamesareused.In1999,ateamofscientistsannouncedtheobservationofwhatappearedtobeelements116(ununhexium)and118(ununoctium).In2001,theteamretracteditsoriginalpaperafterseveralconfirmationexperimentsfailedtoreproducethedesiredresults.In2004,ateamofscientistsfromtheLawrenceLivermoreNationalLaboratoryandtheJointInstituteofNuclearResearchinRussiaannouncedthediscoveryofthesuperheavyelements113(ununtrium,uut)and115(ununpentium,uup).Element117(ununseptium,uus)isnotyetdiscovered.4.WritingtoMultipleSASDataSets(Optional)Alanthanideisanymemberoftheseriesofelementsofincreasingatomicnumbersbeginningwithlanthanum(57)andendingwithytterbium(70).Anactinideisanymemberoftheseriesofelementsthatbeginswithactinium(89)andendswithlawrencium(103).CreatetwoSASdatasets,work.lanthanidesandwork.actinides,fromtheinputdatasetprog2.elements.Eachdatasetshouldcontaininformationaboutthoseelementsinitsseries,with14and15observations,respectively.PartialListingoflanthanidesAtomicObsNameSymbolNumState1CeriumCe58Solid2DysprosiumDy66Solid3ErbiumEr68Solid4EuropiumEu63Solid5GadoliniumGd64SolidPartialListingofactinidesAtomicObsNameSymbolNumState1ActiniumAc89Solid2AmericiumAm95Synthetic3BerkeliumBk97Synthetic4CaliforniumCf98Synthetic5CuriumCm96Synthetic!Thelanthanidesandactinidesarealsoknownastherareearthelements. 2.3SelectingVariablesandObservations2-272.3SelectingVariablesandObservationsObjectives¢ControlwhichvariablesarewrittentoanoutputdatasetduringaDATAstep.¢ControlwhichvariablesarereadfromaninputdatasetduringaDATAstep.¢ControlhowmanyobservationsareprocessedfromaninputdatasetduringaDATAorPROCstep.42ControllingVariableOutputBydefault,theSASSystemwritesallvariablesfromeveryinputdatasettoeveryoutputdataset.IntheDATAstep,theDROPandKEEPstatementscanbeusedtocontrolwhichvariablesarewrittentooutputdatasets.43 2-28Chapter2ControllingInputandOutputTheDROPandKEEPStatements(Review)InputSASdatasetRawdatafilePDVDROPandKEEPstatementsOutputSASdataset45CreatingMultipleSASDataSets(Review)proccontentsdata=prog2.military;run;PartialPROCCONTENTSOutput---AlphabeticListofVariablesandAttributes---#VariableTypeLenƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ6AirportChar403CityChar202CodeChar35CountryChar34StateChar21TypeChar946 2.3SelectingVariablesandObservations2-29CreatingMultipleSASDataSets(Review)dataairforcearmynavymarines;dropType;setprog2.military;ifTypeeq'AirForce'thenoutputairforce;elseifTypeeq'Army'thenoutputarmy;elseifTypeeq'Naval'thenoutputnavy;elseifTypeeq'Marine'thenoutputmarines;run;c02s3d1.sas47CreatingMultipleSASDataSets(Review)PartialLogNOTE:Therewere137observationsreadfromthedatasetPROG2.MILITARY.NOTE:ThedatasetWORK.AIRFORCEhas64observationsand5variables.NOTE:ThedatasetWORK.ARMYhas41observationsand5variables.NOTE:ThedatasetWORK.NAVYhas28observationsand5variables.NOTE:ThedatasetWORK.MARINEShas4observationsand5variables.48 2-30Chapter2ControllingInputandOutputControllingVariableOutputTheDROPandKEEPstatementsapplytoalloutputdatasets.However,whenyoucreatemultipleoutputdatasets,youcanusetheDROP=andKEEP=datasetoptionstowritedifferentvariablestodifferentdatasets.49TheDROP=DataSetOptionTheDROP=datasetoptionexcludesvariablesfromprocessingorfromoutputSASdatasets.WhentheDROP=datasetoptionisassociatedwithanoutputdataset,SASdoesnotwritethespecifiedvariablestotheoutputdataset.However,allvariablesareavailableforprocessing.SAS-data-setSAS-data-set(DROP=(DROP=variable-1variable-2variable-1variable-2……variable-nvariable-n))50!IftheDROP=datasetoptionisassociatedwithaninputdataset,thespecifiedvariablesarenotavailableforprocessing. 2.3SelectingVariablesandObservations2-31TheKEEP=DataSetOptionTheKEEP=datasetoptionspecifiesvariablesforprocessingorforwritingtooutputSASdatasets.WhentheKEEP=datasetoptionisassociatedwithanoutputdataset,onlythespecifiedvariablesarewrittentotheoutputdataset.However,allvariablesareavailableforprocessing.SAS-data-setSAS-data-set(KEEP=(KEEP=variable-1variable-2variable-1variable-2……variable-nvariable-n))51!IftheKEEP=datasetoptionisassociatedwithaninputdataset,onlythespecifiedvariablesareavailableforprocessing.TheDROP=andKEEP=DataSetOptionsInputSASdatasetRawdatafilePDVDROP=andKEEP=DROPandKEEPdatasetoptionsstatementsassociatedwithanoutputdatasetOutputSASdataset52 2-32Chapter2ControllingInputandOutputControllingVariableOutputdataairforce(drop=CodeType)army(drop=CityStateCountryType)navy(drop=Type)marines;setprog2.military;ifTypeeq'AirForce'thenoutputairforce;elseifTypeeq'Army'thenoutputarmy;elseifTypeeq'Naval'thenoutputnavy;elseifTypeeq'Marine'thenoutputmarines;run;c02s3d2.sas53!YoucannotspecifyDROP=orKEEP=datasetoptionsintheOUTPUTstatement.ControllingVariableOutputPartialLogNOTE:Therewere137observationsreadfromthedatasetPROG2.MILITARY.NOTE:ThedatasetWORK.AIRFORCEhas64observationsand4variables.NOTE:ThedatasetWORK.ARMYhas41observationsand2variables.NOTE:ThedatasetWORK.NAVYhas28observationsand5variables.NOTE:ThedatasetWORK.MARINEShas4observationsand6variables.54 2.3SelectingVariablesandObservations2-33ControllingVariableOutputdataairforce(keep=AirportCityStateCountry)army(keep=CodeAirport)navy(keep=CodeAirportCityStateCountry)marines;setprog2.military;ifTypeeq'AirForce'thenoutputairforce;elseifTypeeq'Army'thenoutputarmy;elseifTypeeq'Naval'thenoutputnavy;elseifTypeeq'Marine'thenoutputmarines;run;c02s3d3.sas55Inmanycases,youhaveachoicebetweenusingaDROP=orKEEP=datasetoption(orDROPorKEEPstatements).Typically,choosethedatasetoptionorstatementthatminimizestheamountoftypingasinthisexample:dataairforce(drop=CodeType)army(keep=CodeAirport)navy(drop=Type)marines;setprog2.military;ifTypeeq'AirForce'thenoutputairforce;elseifTypeeq'Army'thenoutputarmy;elseifTypeeq'Naval'thenoutputnavy;elseifTypeeq'Marine'thenoutputmarines;run; 2-34Chapter2ControllingInputandOutputControllingVariableOutputPartialLogNOTE:Therewere137observationsreadfromthedatasetPROG2.MILITARY.NOTE:ThedatasetWORK.AIRFORCEhas64observationsand4variables.NOTE:ThedatasetWORK.ARMYhas41observationsand2variables.NOTE:ThedatasetWORK.NAVYhas28observationsand5variables.NOTE:ThedatasetWORK.MARINEShas4observationsand6variables.56 2.3SelectingVariablesandObservations2-35ControllingVariableInputIntheDATAstep,theDROPandKEEPstatementsapplyonlytooutputSASdatasets.However,theDROP=andKEEP=datasetoptionscanapplytobothinputandoutputSASdatasets.57ControllingVariableInputInputSASdatasetRawDataFileDROP=andKEEP=datasetoptionsin“read”statementPDVDROP=andKEEP=DROPandKEEPdatasetoptionsstatementsassociatedwithanoutputdatasetOutputSASdataset58 2-36Chapter2ControllingInputandOutputControllingVariableInputSASappliesdatasetoptionstoinputdatasetsbeforeit¢evaluatesprogrammingstatements¢appliesdatasetoptionstooutputdatasets.dataarmy(keep=CodeAirport);setprog2.military(drop=CityStateCountry);ifTypeeq'Army'thenoutput;run;c02s3d4.sas59IfaDROPorKEEPstatementisusedatthesametimeasadatasetoption,thestatementisappliedfirst.CompilingtheDATAStepVariablesfromprog2.militaryTypeCodeCityStateCountryAirportdataarmy(keep=CodeAirport);setprog2.military(drop=CityStateCountry);ifTypeeq'Army'thenoutput;run;PDVTypeCodeAirport60... 2.3SelectingVariablesandObservations2-37CompilingtheDATAStepVariablesfromprog2.militaryTypeCodeCityStateCountryAirportdataarmy(keep=CodeAirport);setprog2.military(drop=CityStateCountry);ifTypeeq'Army'thenoutput;run;PDVDTypeCodeAirportarmydescriptorportionCodeAirport$3N861ControllingWhichObservationsAreReadBydefault,SASbeginsprocessingaSASdatasetwiththefirstobservationandcontinuesprocessinguntilendoffile.TheFIRSTOBS=andOBS=datasetoptionscanbeusedtocontrolwhichobservationsareprocessed.YoucanuseFIRSTOBS=andOBS=withinputdatasets.YoucannotuseeitherdatasetoptionintheDATAstatement.62!FIRSTOBS=andOBS=canalsobeusedwithINFILEstatements. 2-38Chapter2ControllingInputandOutputTheOBS=DataSetOptionTheOBS=datasetoptionspecifiesanendingpointforprocessinganinputdataset.SAS-data-setSAS-data-set(OBS=(OBS=nn))Thisoptionspecifiesthenumberofthelastobservationtoprocess,nothowmanyobservationsshouldbeprocessed.63nspecifiesapositiveintegerthatislessthanorequaltothenumberofobservationsinthedataset,orzero.!TheOBS=datasetoptionoverridestheOBS=systemoptionfortheindividualdataset.ToguaranteethatSASprocessesallobservationsfromadataset,youcanusethefollowingsyntax:SAS-data-set(OBS=MAX) 2.3SelectingVariablesandObservations2-39ControllingWhichObservationsAreReadTheOBS=datasetoptionintheSETstatementstopsreadingafterobservation25intheprog2.militarydataset.dataarmy;setprog2.military(obs=25);ifTypeeq'Army'thenoutput;run;64ControllingWhichObservationsAreReadPartialLog60dataarmy;61setprog2.military(obs=25);62ifTypeeq'Army'thenoutput;63run;NOTE:Therewere25observationsreadfromthedatasetPROG2.MILITARY.NOTE:ThedatasetWORK.ARMYhas10observationsand6variables.65 2-40Chapter2ControllingInputandOutputTheFIRSTOBS=DataSetOptionTheFIRSTOBS=datasetoptionspecifiesastartingpointforprocessinganinputdataset.SAS-data-setSAS-data-set(FIRSTOBS=(FIRSTOBS=nn))FIRSTOBS=andOBS=areoftenusedtogethertodefinearangeofobservationstobeprocessed.66nspecifiesapositiveintegerthatislessthanorequaltothenumberofobservationsinthedataset.!TheFIRSTOBS=datasetoptionoverridestheFIRSTOBS=systemoptionfortheindividualdataset. 2.3SelectingVariablesandObservations2-41ControllingWhichObservationsAreReadTheFIRSTOBS=andOBS=datasetoptionsintheSETstatementread15observationsfromprog2.military.Processingbeginswithobservation11andendsafterobservation25.dataarmy;setprog2.military(firstobs=11obs=25);ifTypeeq'Army'thenoutput;run;c02s3d5.sas67ControllingWhichObservationsAreReadPartialLog67dataarmy;68setprog2.military(firstobs=11obs=25);69ifTypeeq'Army'thenoutput;70run;NOTE:Therewere15observationsreadfromthedatasetPROG2.MILITARY.NOTE:ThedatasetWORK.ARMYhas5observationsand6variables.68 2-42Chapter2ControllingInputandOutputControllingWhichObservationsAreReadTheFIRSTOBS=andOBS=datasetoptionscanalsobeusedinaPROCstep.ThefollowingPROCPRINTstepbeginsprocessingthearmydatasetatobservation2andstopsprocessingthearmydatasetafterobservation4.procprintdata=army(firstobs=2obs=4);varCodeAirport;run;69TheDROP=andKEEP=datasetoptionscanbeusedtoexcludevariablesfromprocessingduringaPROCstep:procprintdata=army(drop=CityStateCountryType);run;However,DROP=andKEEP=donotaffecttheorderinwhichthevariablesareprocessed. 2.3SelectingVariablesandObservations2-43ControllingWhichObservationsAreReadPartialLog75procprintdata=army(firstobs=2obs=4);76varCodeAirport;77run;NOTE:Therewere3observationsreadfromthedatasetWORK.ARMY.70ControllingWhichObservationsAreReadPROCPRINTOutputObsCodeAirport2LGFLagunaArmyAirField3SYLRobertsArmyAirField4HGTTusiArmyHeliport71 2-44Chapter2ControllingInputandOutputExercises5.ControllingInputandOutputSizeRecallthattheprog2.elementsdatasetcontainsinformationabouttheknownelementsontheperiodictable.Eachobservationcontainsanelement’sname,symbol,atomicnumber,andstate.ThevalueofStatereferstowhethertheelementisagas,liquid,solid,orsyntheticatroomtemperature.PartialListingofprog2.elementsAtomicNameSymbolNumStateActiniumAc89SolidAluminumAl13SolidAmericiumAm95SyntheticAntimonySb51SolidArgonAr18GasCreatetwoSASdatasets:naturalandsynthetic.Thenaturaldatasetshouldcontaininformationaboutelementsthataresolids,liquids,orgasesatroomtemperature.Itshouldcontainthreevariables(Name,AtomicNum,andState)and91observations.Thesyntheticdatasetshouldcontaintwovariables(NameandAtomicNum)and24observations.PartialListingofnaturalAtomicObsNameNumState1Actinium89Solid2Aluminum13Solid3Antimony51Solid4Argon18Gas5Arsenic33SolidPartialListingofsyntheticAtomicObsNameNum1Americium952Berkelium973Bohrium1074Californium985Curium96 2.4WritingtoanExternalFile2-452.4WritingtoanExternalFileObjectives¢WriteobservationsfromaSASdatasettoacomma-delimitedexternalfile.¢Insertheaderandfooterrecordsintoanexternalfile.74IntroductionTheprog2.maysalesdatasetcontainsinformationabouthouses.Readthisdatasetandwritethedatatoanexternalfile.prog2.maysalesListSellSellDescriptionDateDatePriceColonial1380314001355200Townhouse1389414016241200Townhouse1410814392238100Ranch1458514736219400Victorian148051510635820075 2-46Chapter2ControllingInputandOutputTheODSCSVALLStatementODSstatementsareglobalinmostrespects.TheyenableyoutomanageoutputobjectsproducedbyproceduresortheDATAstep.TheODSCSVALLstatementcreatesacomma-delimitedfilefromoutputobjectswiththesecharacteristics:°valuescontaininglettersorspecialcharactersareenclosedinmatchingquotes°titlesandfootnotesarepreserved.ODSCSVALLODSCSVALLFILE=FILE=file-specificationfile-specification;;ODSCSVALLCLOSE;ODSCSVALLCLOSE;!CSVALLisaSAS®9option.76TheadditionalcodecanbeanyDATAorPROCstepthatproducesoutputobjects.TheODSCSVALLStatementTocreatethedesiredexternalfile,placeaPRINTprocedurestepbetweentheODSstatements.odscsvallfile='raw-data-file';title1;footnote1'Data:PROG2.MAYSALES';procprintnoobsdata=prog2.maysales;formatlistdateselldatedate9.;run;odscsvallclose;77c02s4d1.sas 2.4WritingtoanExternalFile2-47TheODSCSVALLStatementraw-data-file"Description","ListDate","SellDate","SellPrice""Colonial","16OCT1997","02MAY1998",355200"Townhouse","15JAN1998","17MAY1998",241200"Townhouse","17AUG1998","28MAY1999",238100"Ranch","07DEC1999","06MAY2000",219400"Victorian","14JUL2000","11MAY2001",358200Data:PROG2.MAYSALES78!InordertoviewtheexternalfilefromaninteractiveSASsession,youcanusetheResultsViewerortheFSLISTprocedure(describedlaterinthissection).!Ifadialogboxpromptsyoutochoosetoeitheropenorsavethefile,saveitandthenopenthefilewithanappropriateapplication.Openingthefileinresponsetothepromptmightinadvertentlyleavethefileopenandlockedagainstfurtherprocessing. 2-48Chapter2ControllingInputandOutputTheDATAStepYoucanusetheDATAsteptowrite¢acustomreport¢datatoanexternalfiletobereadbyotherprogramminglanguagesorsoftware.79YoucanalsousetheEXPORTproceduretoreaddatafromaSASdatasetandwriteittoanexternaldatasource.Externaldatasourcescanincludedatabasetables,PCfiles,spreadsheets,anddelimitedexternalfiles.!PROCEXPORTisavailableinthefollowingoperatingenvironments:UNIX,OpenVMS,andWindows. 2.4WritingtoanExternalFile2-49TheDATAStepREADINGFROMWRITINGTOANEXTERNALFILEANEXTERNALFILETheDATAstatementTheDATAstatementbeginstheDATAstep.beginstheDATAstep.TheINFILEstatementidentifiesTheFILEstatementidentifiesanexternalfiletoreadanexternalfiletowritewithanINPUTstatement.withaPUTstatement.TheINPUTstatementdescribesThePUTstatementdescribesthearrangementofvaluesthearrangementofvaluesintheinputdatarecord.intheoutputdatarecord.82TheDATAStatementUsually,theDATAstatementspecifiesatleastonedatasetnamethattheSASSystemusestocreateanoutputdataset.Usingthe_NULL_keywordasthedatasetnamecausesSAStoexecutetheDATAstepwithoutwritingobservationstoadataset.DATADATA_NULL__NULL_;;83 2-50Chapter2ControllingInputandOutputTheFILEStatementTheFILEstatementcanbeusedtospecifytheoutputdestinationforsubsequentPUTstatements.GeneralformoftheFILEstatement:FILEFILEfile-specificationfile-specification<>;;YoucanusetheFILEstatementinconditionalprocessing(IF-THEN/ELSEorSELECT)becauseitisexecutable.84file-specificationidentifiesanexternalfilethattheDATAstepusestowriteoutputfromaPUTstatement.Itcanhavetheseforms:'external-file'specifiesthephysicalnameofanexternalfile,whichisenclosedinquotationmarks.Thephysicalnameisthenamebywhichtheoperatingenvironmentrecognizesthefile.filerefspecifiesthefilereferenceforanexternalfile.YoumusthavepreviouslyassociatedafilerefwithanexternalfileinaFILENAMEstatementorfunction,orinanappropriateoperatingenvironmentcommand.LOGisareservedfilereferencethatdirectstheoutputfromsubsequentPUTstatementstothelog.PRINTisareservedfilereferencethatdirectstheoutputfromsubsequentPUTstatementstothesameprintfileastheoutputthatisproducedbySASprocedures.!Thedefaultfile-specificationisLOG.YoucanusemultipleFILEstatementstowritetomorethanoneexternalfileinasingleDATAstep.YoucanusePRINTasyourinitialfile-specificationtoverifythecontentsofyouroutputfilebeforecreatinganexternalfile. 2.4WritingtoanExternalFile2-51TheFILENAMEstatementassociatesaSASfilereferencewithanexternalfileoranoutputdevice.FILENAMEfileref'external-file';filerefspecifiesanySASname.device-typespecifiesthetypeofdeviceortheaccessmethodthatisusedifthefilerefpointstoaninputoroutputdeviceorlocationthatisnotaphysicalfile.'external-file'specifiesaphysicalnameofanexternalfile.Thephysicalnameisthenamethatisrecognizedbytheoperatingenvironment.host-optionsspecifydetails,suchasfileattributesandprocessingattributes,thatarespecifictoyouroperatingenvironment.ThePUTStatementThePUTstatementcanwritelinestotheexternalfilethatisspecifiedinthemostrecentlyexecutedFILEstatement.GeneralformofthePUTstatement:PUTPUTvariable-1variable-2…variable-nvariable-1variable-2…variable-n;;Withsimplelistoutput,youlistthenamesofthevariableswhosevaluesyouwantwritten.ThePUTstatementwritesavariablevalue,insertsasingleblank,andthenwritesthenextvalue.85Inadditiontovariablevalues,youcanalsouseaquotedcharacterstringtospecifyastringoftexttowrite.Whenaquotedcharacterstringiswritten,SASdoesnotautomaticallyinsertablankspace.Theoutputpointerstopsatthecolumnthatimmediatelyfollowsthelastcharacterinthestring.Thevaluesofcharactervariablesareleft-alignedinthefield;leadingandtrailingblanksareremoved.AnullPUTstatementcanbeusedtooutputablankline:put; 2-52Chapter2ControllingInputandOutputModifiedListOutputModifiedlistoutputincreasestheversatilityofthePUTstatementbecauseyoucanspecifyaSASformattocontrolhowthevariablevaluesarewritten.Tousemodifiedlistoutput,usethecolon(:)formatmodifierinthePUTstatementbetweenthevariablenameandtheformat.PUTPUTvariable-1variable-1::format-1.format-1.variable-2variable-2::format-2.format-2.……variable-nvariable-n::format-n.format-n.;;86format-1.throughformat-n.specifyformatstousewhenthedatavaluesarewritten.YoucanspecifyeitherSASformatsoruser-definedformats.ThecolonformatmodifierenablesyoutospecifyaformatthatthePUTstatementusestowritethevariablevalue.Allleadingandtrailingblanksaredeleted,andeachvalueisfollowedbyasingleblank.!SeeSASdocumentationforacompletelistofSASformatsandtheirusage. 2.4WritingtoanExternalFile2-53WritingtoanExternalFiledata_null_;setprog2.maysales;file'raw-data-file';putDescriptionListDate:date9.SellDate:date9.SellPrice;run;Whyisthe$omittedafterDescriptioninthePUTstatement?c02s4d2.sas87!AFILENAMEstatementcanbeusedtoassociatethefilerefEXTFILEwiththerawdatafile:filenameextfile'raw-data-file';TheFILEstatementcanbesubsequentlyrevised:fileextfile;WritingtoanExternalFilePartialLogNOTE:5recordswerewrittentothefile'raw-data-file'.Theminimumrecordlengthwas32.Themaximumrecordlengthwas36.NOTE:Therewere5observationsreadfromthedatasetPROG2.MAYSALES.CanyouusePROCPRINTtoviewtherawdatafile?88 2-54Chapter2ControllingInputandOutputTheFSLISTProcedureTheFSLISTprocedureenablesyoutobrowseexternalfileswithinaninteractiveSASsession.YoucannotusetheFSLISTproceduretobrowseSASdatasets.PROCFSLISTPROCFSLISTFILEREF=FILEREF=file-specificationfile-specification<