sas programming manipulation data with the data setp

sas programming manipulation data with the data setp

ID:7323476

大小:2.87 MB

页数:635页

时间:2018-02-11

上传者:U-5649
sas programming manipulation data with the data setp_第1页
sas programming manipulation data with the data setp_第2页
sas programming manipulation data with the data setp_第3页
sas programming manipulation data with the data setp_第4页
sas programming manipulation data with the data setp_第5页
资源描述:

《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<>;;RUN;RUN;RemembertoclosetheFSLISTwindowwhenyoufinishbrowsingyourexternalfile.89file-specificationspecifiestheexternalfiletobrowse.Youmustspecifyfile-specification.Itcanbeoneofthefollowing:'external-file'isthecompleteoperatingenvironmentfilespecificationfortheexternalfile.Youmustenclosethenameinquotationmarks.filerefspecifiesthefilerefofanexternalfile.YoumusthavepreviouslyassociatedthefilerefwithanexternalfileinaFILENAMEstatementorfunction,orinanappropriateoperatingenvironmentcommand.!AliasesforFILEREF=includeFILE=,DDNAME=,andDD=.Youcanuseanytexteditoravailableforyouroperatingenvironmenttoviewtheexternalfile.Forinstance,WindowsuserscanuseNotepadorMicrosoftWord,UNIXuserscanuseemacsorvi,andz/OSuserscanuseISPF. 2.4WritingtoanExternalFile2-55ReadingfromanExternalFileprocfslistfileref='raw-data-file';run;PROCFSLISTOutputColonial16OCT199702MAY1998355200Townhouse15JAN199817MAY1998241200Townhouse17AUG199828MAY1999238100Ranch07DEC199906MAY2000219400Victorian14JUL200011MAY2001358200Howcanyouaddasinglerowofcolumnheadersbeforetherowsofdata?90The_N_AutomaticVariableThe_N_automaticvariableiscreatedbyeveryDATAstep.EachtimethattheDATAsteploopspasttheDATAstatement,_N_isincrementedby1.Therefore,thevalueof_N_representsthenumberoftimesthattheDATAstepiterated._N_isaddedtotheProgramDataVector,butitisnotoutput.91 2-56Chapter2ControllingInputandOutputWritingtoanExternalFiledata_null_;setprog2.maysales;file'raw-data-file';if_N_=1thenput'Description''ListDate''SellDate''SellPrice';putDescriptionListDate:date9.SellDate:date9.SellPrice;run;WhyisthesecondPUTstatementnotcontainedinanELSEstatement?c02s4d3.sas92TheIF-THENstatementshownabovecouldalsobewrittenasfollows:if_N_=1thenput'DescriptionListDateSellDateSellPrice';Exercisecautionwhenindentingorbreakinglineswithinaquotedstring.ThefollowingPUTstatementproducesunexpectedresults:if_N_=1thenput'DescriptionListDateSellDateSellPrice';Becauseoftheindentionwithinthequotedstring,thefollowingresultsareproduced:DescriptionListDateSellDateSellPrice 2.4WritingtoanExternalFile2-57WritingtoanExternalFileprocfslistfileref='raw-data-file';run;PROCFSLISTOutputDescriptionListDateSellDateSellPriceColonial16OCT199702MAY1998355200Townhouse15JAN199817MAY1998241200Townhouse17AUG199828MAY1999238100Ranch07DEC199906MAY2000219400Victorian14JUL200011MAY2001358200Howcanyouaddafooterrecordaftertherowsofdata?93TheEND=OptionintheSETStatementTheEND=optionintheSETstatementcreatesandnamesatemporaryvariablethatactsasanend-of-fileindicator.SETSETSAS-data-setSAS-data-setEND=END=variablevariable<>;;Thistemporaryvariableisinitializedto0.WhentheSETstatementreadsthelastobservationofthedatasetlisted,thevalueofthevariableissetto1.Thevariableisnotaddedtoanynewdataset.94END=isanoptionintheSETstatement.Itisnotadatasetoption;itisnotenclosedinparentheses. 2-58Chapter2ControllingInputandOutputWritingtoanExternalFiledata_null_;setprog2.maysalesend=IsLast;file'raw-data-file';if_N_=1thenput'Description''ListDate''SellDate''SellPrice';putDescriptionListDate:date9.SellDate:date9.SellPrice;ifIsLast=1thenput'Data:PROG2.MAYSALES';run;c02s4d4.sas95ifIsLast=1thenput'Data:PROG2.MAYSALES';couldbereplacedwithifIsLastthenput'Data:PROG2.MAYSALES';WritingtoanExternalFile:Compilationdata_null_;setprog2.maysalesend=IsLast;file'raw-data-file';if_N_=1thenput'Description''ListDate''SellDate''SellPrice';putDescriptionListDate:date9.SellDate:date9.SellPrice;ifIsLast=1thenput'Data:PROG2.MAYSALES';run;PDVDDIsLastDescriptionListDateSellDateSellPrice_N_96... 2.4WritingtoanExternalFile2-59WritingtoanExternalFile:Executiondata_null_;setprog2.maysalesend=IsLast;PartialListingofprog2.maysalesfile'raw-data-file';ListSellif_N_=1thenDescriptionDateDateput'Description''ListDate''SellDate''SellPrice';Colonial1380314001putDescriptionTownhouse1389414016ListDate:date9.Townhouse1410814392SellDate:date9.Ranch1458514736SellPrice;Victorian1480515106ifIsLast=1thenInitializePDVtomissingput'Data:PROG2.MAYSALES';run;PDVDDIsLastDescriptionListDateSellDateSellPrice_N_0...197...WritingtoanExternalFile:Executiondata_null_;setprog2.maysalesend=IsLast;PartialListingofprog2.maysalesfile'raw-data-file';ListSellif_N_=1thenDescriptionDateDateput'Description''ListDate''SellDate''SellPrice';Colonial1380314001putDescriptionTownhouse1389414016ListDate:date9.Townhouse1410814392SellDate:date9.Ranch1458514736SellPrice;Victorian1480515106ifIsLast=1thenput'Data:PROG2.MAYSALES';run;PDVDDIsLastDescriptionListDateSellDateSellPrice_N_0Colonial1380314001355200198... 2-60Chapter2ControllingInputandOutputWritingtoanExternalFile:Executiondata_null_;setprog2.maysalesend=IsLast;PartialListingofprog2.maysalesfile'raw-data-file';ListSellif_N_=1thenDescriptionDateDateput'Description''ListDate''SellDate''SellPrice';Colonial1380314001putDescriptionTownhouse1389414016ListDate:date9.Townhouse1410814392SellDate:date9.Ranch1458514736SellPrice;Victorian1480515106ifIsLast=1thenput'Data:PROG2.MAYSALES';run;PDVDDIsLastDescriptionListDateSellDateSellPrice_N_0Colonial1380314001355200199...WritingtoanExternalFile:Executiondata_null_;setprog2.maysalesend=IsLast;PartialListingofprog2.maysalesTruefile'raw-data-file';ListSellif_N_=1thenDescriptionDateDateput'Description''ListDate''SellDate''SellPrice';Colonial1380314001putDescriptionTownhouse1389414016ListDate:date9.Townhouse1410814392SellDate:date9.Ranch1458514736SellPrice;Victorian1480515106ifIsLast=1thenput'Data:PROG2.MAYSALES';run;PDVDDIsLastDescriptionListDateSellDateSellPrice_N_0Colonial13803140013552001100Writeheaderinformationtoexternalfile.... 2.4WritingtoanExternalFile2-61WritingtoanExternalFile:Executiondata_null_;setprog2.maysalesend=IsLast;PartialListingofprog2.maysalesfile'raw-data-file';ListSellif_N_=1thenDescriptionDateDateput'Description''ListDate''SellDate''SellPrice';Colonial1380314001putDescriptionTownhouse1389414016ListDate:date9.Townhouse1410814392SellDate:date9.Ranch1458514736SellPrice;Victorian1480515106ifIsLast=1thenput'Data:PROG2.MAYSALES';run;PDVDDIsLastDescriptionListDateSellDateSellPrice_N_0Colonial13803140013552001101Writefirstlineofdatatoexternalfile.WritingtoanExternalFile:ExecutionPartialListingofraw-data-fileDescriptionListDateSellDateSellPriceColonial16OCT199702MAY1998355200102 2-62Chapter2ControllingInputandOutputWritingtoanExternalFile:Executiondata_null_;setprog2.maysalesend=IsLast;PartialListingofprog2.maysalesfile'raw-data-file';ListSellif_N_=1thenDescriptionDateDateput'Description''ListDate''SellDate''SellPrice';Colonial1380314001putDescriptionTownhouse1389414016ListDate:date9.Townhouse1410814392FalseSellDate:date9.Ranch1458514736SellPrice;Victorian1480515106ifIsLast=1thenput'Data:PROG2.MAYSALES';run;PDVDDIsLastDescriptionListDateSellDateSellPrice_N_0Colonial13803140013552001103...WritingtoanExternalFile:Executiondata_null_;setprog2.maysalesend=IsLast;PartialListingofprog2.maysalesfile'raw-data-file';ListSellif_N_=1thenDescriptionDateDateput'Description''ListDate''SellDate''SellPrice';Colonial1380314001putDescriptionTownhouse1389414016ListDate:date9.Townhouse1410814392SellDate:date9.Ranch1458514736SellPrice;Victorian1480515106ifIsLast=1thenput'Data:PROG2.MAYSALES';run;AutomaticreturnPDVDDIsLastDescriptionListDateSellDateSellPrice_N_0Colonial13803140013552001104... 2.4WritingtoanExternalFile2-63WritingtoanExternalFile:Executiondata_null_;ContinueexecutingDATAsetprog2.maysalesend=IsLast;PartialListingofstepuntilthelastprog2.maysalesfile'raw-data-file';observationisreadListSellif_N_=1thenDescriptionDateDateput'Description''ListDate''SellDate''SellPrice';Colonial1380314001putDescriptionTownhouse1389414016ListDate:date9.Townhouse1410814392TrueSellDate:date9.Ranch1458514736SellPrice;Victorian1480515106ifIsLast=1thenput'Data:PROG2.MAYSALES';run;PDVDDIsLastDescriptionListDateSellDateSellPrice_N_1Victorian14805151063582005105WritingtoanExternalFileprocfslistfileref='raw-data-file';run;PROCFSLISTOutputDescriptionListDateSellDateSellPriceColonial16OCT199702MAY1998355200Townhouse15JAN199817MAY1998241200Townhouse17AUG199828MAY1999238100Ranch07DEC199906MAY2000219400Victorian14JUL200011MAY2001358200Data:PROG2.MAYSALES106 2-64Chapter2ControllingInputandOutputSpecifyinganAlternateDelimiterUsetheDLM=optionintheFILEstatementtocreateafilewithanalternatedelimiter(otherthanablank).FILEFILEfile-specificationfile-specificationDLM='DLM='quoted-stringquoted-string''<>;;Youcanalsospecifyacharactervariablewhosevaluecontainsyourdelimiter,insteadofaquotedstring.!DLM=isanaliasforDELIMITER=.107'quoted-string'specifiesanalternatedelimiter(otherthanthedefault,ablank)tobeusedforsimpleormodifiedlistoutput.Althoughacharacterstringorcharactervariableisaccepted,onlythefirstcharacterofthestringorvariableisusedastheoutputdelimiter.TospecifyatabcharacteronaPCoronUNIX,usedlm='09'x.Tospecifyatabcharacteronz/OS,usedlm='05'x. 2.4WritingtoanExternalFile2-65WritingtoanExternalFiledata_null_;setprog2.maysalesend=IsLast;file'raw-data-file'dlm=',';if_N_=1thenput'Description,ListDate,''SellDate,SellPrice';putDescriptionListDate:date9.SellDate:date9.SellPrice;ifIsLast=1thenput'Data:PROG2.MAYSALES';run;c02s4d5.sas108TheIF-THENstatementshownabovecanalsobewrittenasfollows:if_N_=1thenput'Description,ListDate,SellDate,SellPrice';WritingtoanExternalFileprocfslistfileref='raw-data-file';run;PROCFSLISTOutputDescription,ListDate,SellDate,SellPriceColonial,16OCT1997,02MAY1998,355200Townhouse,15JAN1998,17MAY1998,241200Townhouse,17AUG1998,28MAY1999,238100Ranch,07DEC1999,06MAY2000,219400Victorian,14JUL2000,11MAY2001,358200Data:PROG2.MAYSALES109 2-66Chapter2ControllingInputandOutputExercises6.WritingtoanExternalFileThedatasetprog2.visitscontainsinformationaboutpatientswhovisitedaphysician’soffice.Createacomma-delimitedexternalfilecontainingtheinformationfromprog2.visits.Thenameofyourexternalfilewilldependonyouroperatingenvironment.ThevaluesofDateshouldbeoutputusingtheMMDDYY10.format.Thefirstrecordintheexternalfileshouldcontaincolumnheaders.Thelastrecordintheexternalfileshouldcontainafooter.!IfyouelecttousetheDATAsteptocreatetheexternalfile,usetheFSLISTproceduretoviewyourexternalfile.RemembertoclosetheFSLISTwindowwhenyoufinishviewingthefile.!IfyouelecttouseODStocreatetheexternalfile,andadialogboxpromptsyoutochoosetoeitheropenorsavethefile,saveitandthenopenthefileoutsidetheSASenvironment(usingMicrosoftExceloranotherappropriateapplication).Openingthefileinresponsetothepromptmightleavethefileopenandlockedagainstfurtherprocessing.Listingofprog2.visitsSSNDateFee243-88-436422JUL2001864.15193-27-981522JUL2001621.50278-80-579323JUL20011228.75926-36-394824JUL2001897.25618-96-176424JUL2001897.25679-72-175925JUL2001952.50618-96-176426JUL2001731.50679-72-175926JUL20011781.25236-76-157429JUL2001897.25345-10-391229JUL20011228.75679-72-175930JUL20011339.25278-80-579330JUL2001676.25!ThevaluesofDatearedisplayedwithapermanentlyassignedDATE9.format.ThevaluesofDateshouldnotbeoutputusingthisformat. 2.4WritingtoanExternalFile2-67DesiredOutput(ExternalFile)SSN,Date,Fee243-88-4364,07/22/2001,864.15193-27-9815,07/22/2001,621.5278-80-5793,07/23/2001,1228.75926-36-3948,07/24/2001,897.25618-96-1764,07/24/2001,897.25679-72-1759,07/25/2001,952.5618-96-1764,07/26/2001,731.5679-72-1759,07/26/2001,1781.25236-76-1574,07/29/2001,897.25345-10-3912,07/29/2001,1228.75679-72-1759,07/30/2001,1339.25278-80-5793,07/30/2001,676.25Data:PROG2.VISITS 2-68Chapter2ControllingInputandOutput2.5SolutionstoExercises1.OutputtingMultipleObservationsdatarotate;dropQtr1Qtr2Qtr3Qtr4;setprog2.donate;Qtr=1;Amount=Qtr1;output;Qtr=2;Amount=Qtr2;output;Qtr=3;Amount=Qtr3;output;Qtr=4;Amount=Qtr4;output;run;procprintdata=rotate;run;2.UsingConditionalLogictoOutputMultipleObservations(Optional)databuyhistory(keep=IDMethod);lengthMethod$13;setprog2.ffmethod;ifInterneteq'Y'thendo;Method='Internet';output;end;ifTelephoneeq'Y'thendo;Method='Telephone';output;end;ifTravelAgencyeq'Y'thendo;Method='TravelAgency';output;end;run;procprintdata=buyhistory;varIDMethod;run; 2.5SolutionstoExercises2-693.WritingtoMultipleSASDataSetsdatagasliquidsolidsynthetic;dropState;setprog2.elements;ifStateeq'Gas'thenoutputgas;elseifStateeq'Liquid'thenoutputliquid;elseifStateeq'Solid'thenoutputsolid;elseifStateeq'Synthetic'thenoutputsynthetic;run;procprintdata=liquid;run;4.WritingtoMultipleSASDataSets(Optional)datalanthanidesactinides;setprog2.elements;ifAtomicNumge57andAtomicNumle70thenoutputlanthanides;elseifAtomicNumge89andAtomicNumle103thenoutputactinides;run;procprintdata=lanthanides;run;procprintdata=actinides;run; 2-70Chapter2ControllingInputandOutput5.ControllingInputandOutputSizedatanatural(keep=NameAtomicNumState)synthetic(keep=NameAtomicNum);setprog2.elements;ifStateeq'Synthetic'thenoutputsynthetic;elseoutputnatural;run;procprintdata=natural;run;procprintdata=synthetic;run;AlternateSolution:datanatural(keep=NameAtomicNumState)synthetic(keep=NameAtomicNum);setprog2.elements;ifStatein('Solid','Liquid','Gas')thenoutputnatural;elseoutputsynthetic;run;procprintdata=natural;run;procprintdata=synthetic;run; 2.5SolutionstoExercises2-716.WritingtoanExternalFiledata_null_;/*TheEND=optionintheSETstatementisusedtodeterminewhenSASreadsthelastobservationfromPROG2.VISITS.*/setprog2.visitsend=IsLast;/*TheDLM=optionintheFILEstatementseparatesthedatavalueswithcommas.*/file'visits.csv'dlm=',';/*The_N_automaticvariableisusedtowritecolumnheadersatthetopoftherawdatafile.*/if_N_=1thenput'SSN,Date,Fee';putSSNDate:mmddyy10.Fee;/*ThevalueofISLAST,createdusingtheEND=optionintheSETstatement,isusedtocreateafooteratthebottomoftherawdatafile.*/ifIsLast=1thenput'Data:PROG2.VISITS';run;/*TheFILEstatementisapplicabletotheWindowsandUNIXoperatingenvironments.z/OSusersshoulduse:file'.prog2.rawdata(visits)'dlm=',';*/procfslistfileref='visits.csv';run;/*ThePROCFSLISTstatementisapplicabletotheWindowsandUNIXoperatingenvironments.z/OSusersshoulduse:procfslistfileref='.prog2.rawdata(visits)';run*/ 2-72Chapter2ControllingInputandOutput®AlternateSolution(SAS9):/*Thefile'visits.csv'isapplicabletotheWindowsandUNIXoperatingenvironments.z/OSusersshoulduse'.prog2.rawdata(visits)'inboththeODSandPROCFSLISTstatements.*/odscsvallfile='visits.csv';title1;footnote1'Data:PROG2.VISITS';procprintnoobsdata=prog2.visits;formatDatemmddyy10.;run;odscsvallclose; Chapter3SummarizingData3.1CreatinganAccumulatingTotalVariable.....................................................................3-33.2AccumulatingTotalsforaGroupofData...................................................................3-173.3SolutionstoExercises.................................................................................................3-43 3-2Chapter3SummarizingData 3.1CreatinganAccumulatingTotalVariable3-33.1CreatinganAccumulatingTotalVariableObjectives¢UnderstandhowtheSASSysteminitializesthevalueofavariableinthePDV.¢PreventreinitializationofavariableinthePDV.¢Createanaccumulatingvariable.3CreatinganAccumulatingVariableSaleDateSaleAmtTheSASdatasetprog2.daysales01APR2001498.49containsdailysalesdata02APR2001946.50foraretailstore.Thereis03APR2001994.97oneobservationforeach04APR2001564.59dayinAprilshowingthe05APR2001783.01date(SaleDate)and06APR2001228.82thetotalreceiptsforthat07APR2001930.57day(SaleAmt).08APR2001211.4709APR2001156.2310APR2001117.6911APR2001374.7312APR2001252.734 3-4Chapter3SummarizingDataCreatinganAccumulatingVariableThestoremanageralsowantstoseearunningtotalofsalesforthemonthasofeachday.PartialOutputSaleSaleDateAmtMth2Dte01APR2001498.49498.4902APR2001946.501444.9903APR2001994.972439.9604APR2001564.593004.5505APR2001783.013787.565!TheinputSASdatasetmustbesortedbyDateforthefollowingmethodtowork.CreatingMth2DteBydefault,variablescreatedwithanassignmentstatementareinitializedtomissingatthetopoftheDATAstep.Mth2Dte=Mth2Dte+SaleAmt;Anaccumulatingvariablemustretainitsvaluefromoneobservationtothenext.6 3.1CreatinganAccumulatingTotalVariable3-5TheRETAINStatementGeneralformoftheRETAINstatement:RETAINRETAINvariable-namevariable-name<…>…;;TheRETAINstatementpreventsSASfromre-initializingthevaluesofnewvariablesatthetopoftheDATAstep.PreviousvaluesofretainedvariablesareavailableforprocessingacrossiterationsoftheDATAstep.7TheRETAINStatementTheRETAINstatement¢retainsthevalueofthevariableinthePDVacrossiterationsoftheDATAstep¢initializestheretainedvariabletomissingbeforethefirstexecutionoftheDATAstepifaninitialvalueisnotspecified¢isacompile-time-onlystatement.8TheRETAINstatementhasnoeffectonvariablesthatarereadwithSET,MERGE,orUPDATEstatements;valuesreadfromSASdatasetsareautomaticallyretained.AvariablereferencedintheRETAINstatementappearsintheoutputSASdatasetonlyifitisgivenaninitialvalueorreferencedelsewhereintheDATAstep. 3-6Chapter3SummarizingDataRetainMth2DteandSetanInitialValueretainMth2Dte0;Ifyoudonotsupplyaninitialvalue,allthevaluesofMth2Dtewillbemissing.9CreatingAccumulatingVariables:Compilationdatamnthtot;setprog2.daysales;retainMth2Dte0;Mth2Dte=Mth2Dte+SaleAmt;run;PDVRSaleDateSaleAmtMth2Dte10... 3.1CreatinganAccumulatingTotalVariable3-7CreatingAccumulatingVariables:ExecutionSaleDateSaleAmtdatamnthtot;setprog2.daysales;15066498.49retainMth2Dte0;15067946.50Mth2Dte=Mth2Dte+SaleAmt;15068994.97run;15069564.5915070783.01InitializePDVPDVRSaleDateSaleAmtMth2Dte..011...CreatingAccumulatingVariables:ExecutionSaleDateSaleAmtdatamnthtot;setprog2.daysales;15066498.49retainMth2Dte0;15067946.50Mth2Dte=Mth2Dte+SaleAmt;15068994.97run;15069564.5915070783.01PDVRSaleDateSaleAmtMth2Dte15066498.49012... 3-8Chapter3SummarizingDataCreatingAccumulatingVariables:ExecutionSaleDateSaleAmtdatamnthtot;setprog2.daysales;15066498.49retainMth2Dte0;15067946.50Mth2Dte=Mth2Dte+SaleAmt;15068994.97run;15069564.5915070783.010+498.49PDVRSaleDateSaleAmtMth2Dte15066498.49498.4913...CreatingAccumulatingVariables:ExecutionSaleDateSaleAmtdatamnthtot;setprog2.daysales;15066498.49retainMth2Dte0;15067946.50Mth2Dte=Mth2Dte+SaleAmt;15068994.97run;15069564.59Automatic15070783.01AutomaticoutputreturnPDVRSaleDateSaleAmtMth2Dte15066498.49498.49Writeobservationtomnthtot.14... 3.1CreatinganAccumulatingTotalVariable3-9CreatingAccumulatingVariables:ExecutionSaleDateSaleAmtdatamnthtot;setprog2.daysales;15066498.49retainMth2Dte0;15067946.50Mth2Dte=Mth2Dte+SaleAmt;15068994.97run;15069564.59Donotre-initialize15070783.01PDVtomissingPDVRSaleDateSaleAmtMth2Dte15066498.49498.4915...CreatingAccumulatingVariables:ExecutionSaleDateSaleAmtdatamnthtot;setprog2.daysales;15066498.49retainMth2Dte0;15067946.50Mth2Dte=Mth2Dte+SaleAmt;15068994.97run;15069564.5915070783.01PDVRSaleDateSaleAmtMth2Dte15067946.50498.4916... 3-10Chapter3SummarizingDataCreatingAccumulatingVariables:ExecutionSaleDateSaleAmtdatamnthtot;setprog2.daysales;15066498.49retainMth2Dte0;15067946.50Mth2Dte=Mth2Dte+SaleAmt;15068994.97run;15069564.5915070783.01498.49+946.50PDVRSaleDateSaleAmtMth2Dte15067946.501444.9917...CreatingAccumulatingVariables:ExecutionSaleDateSaleAmtdatamnthtot;setprog2.daysales;15066498.49retainMth2Dte0;15067946.50Mth2Dte=Mth2Dte+SaleAmt;15068994.97run;15069564.59Automatic15070783.01AutomaticoutputreturnPDVRSaleDateSaleAmtMth2Dte15067946.501444.9918Writeobservationtomnthtot.... 3.1CreatinganAccumulatingTotalVariable3-11CreatingAccumulatingVariables:ExecutionSaleDateSaleAmtdatamnthtot;setprog2.daysales;15066498.49retainMth2Dte0;15067946.50Mth2Dte=Mth2Dte+SaleAmt;15068994.97run;15069564.59Donotre-initialize15070783.01PDVtomissingPDVRSaleDateSaleAmtMth2Dte15067946.501444.9919...CreatingAccumulatingVariables:ExecutionSaleDateSaleAmtdatamnthtot;setprog2.daysales;15066498.49retainMth2Dte0;15067946.50Mth2Dte=Mth2Dte+SaleAmt;15068994.97run;15069564.5915070783.01ContinueprocessingPDVRuntilendofSASdatasetSaleDateSaleAmtMth2Dte15067946.501444.9920 3-12Chapter3SummarizingDataCreatingAccumulatingVariablesprocprintdata=mnthtotnoobs;formatSaleDatedate9.;run;PartialPROCPRINTOutputSaleSaleDateAmtMth2Dte01APR2001498.49498.4902APR2001946.501444.9903APR2001994.972439.9604APR2001564.593004.5505APR2001783.013787.5621AccumulatingTotals:MissingValuesdatamnthtot;setprog2.daysales;retainMth2Dte0;Mth2Dte=Mth2Dte+SaleAmt;run;WhathappensiftherearemissingvaluesforSaleAmt?22 3.1CreatinganAccumulatingTotalVariable3-13UndesirableOutputSaleSaleDateAmtMth2Dte01APR2001498.49498.4902APR2001..03APR2001994.97.04APR2001564.59.05APR2001783.01.SubsequentvaluesofMissingvalueMth2Dtearemissing23Theresultofanymathematicaloperationonamissingvalueismissing.Withtheabovecode,onemissingvalueforSaleAmtcausesallsubsequentvaluesofMth2Dtetobemissing.YoucansolvethisproblembyusingtheSUMfunctionintheassignmentstatement:Mth2Dte=sum(Mth2Dte,SaleAmt);SeeChapter5,“DataTransformations,”fordetails.However,thesumstatementisamoreefficientsolutionbecauseitdoesnotrequireSAStoinvoketheSUMfunction. 3-14Chapter3SummarizingDataTheSumStatementWhenyoucreateanaccumulatingvariable,analternativetotheRETAINstatementisthesumstatement.Generalformofthesumstatement:variablevariable++expressionexpression;;24!Liketheassignmentstatement,thesumstatementdoesnotbeginwithakeyword.TheSumStatementThesumstatement¢createsthevariableontheleftsideoftheplussignifitdoesnotalreadyexist¢initializesthevariabletozerobeforethefirstiterationoftheDATAstep¢automaticallyretainsthevariable¢addsthevalueofexpressiontothevariableatexecution¢ignoresmissingvalues.25 3.1CreatinganAccumulatingTotalVariable3-15AccumulatingTotals:MissingValuesdatamnthtot2;setprog2.daysales2;Mth2Dte+SaleAmt;run;26AccumulatingTotals:MissingValuesprocprintdata=mnthtot2noobs;formatSaleDatedate9.;run;PartialPROCPRINTOutputSaleDateSaleAmtMth2Dte01APR2001498.49498.4902APR2001.498.4903APR2001994.971493.4604APR2001564.592058.0505APR2001783.012841.0627c03s1d1.sas 3-16Chapter3SummarizingDataExercises1.CreatinganAccumulatingTotalVariableThedatasetprog2.statescontainsthestatename(State),thedatethestateenteredtheUnitedStates(EnterDate),andthesizeofthestateinsquaremiles(Size)forall50U.S.states.ThedatasetissortedbyEnterDate.PartialListingofprog2.statesStateEnterDateSizeDelaware07DEC17871955Pennsylvania12DEC178744820NewJersey18DEC17877418Georgia02JAN178857918Connecticut09JAN17884845Massachusetts06FEB17887838Maryland28APR17889775SouthCarolina23MAY178830111!ThevariableEnterDatehasthepermanentformatDATE9.CreatetheSASdatasetwork.usareathatcontainsthenewvariableTotArea,whichisarunningtotalofthesizeoftheUnitedStatesaseachstatewasadded,andthenewvariableNumStates,whichshowshowmanystateswereintheUnitedStatesatthatpoint.PartialListingofwork.usareaNumObsStateEnterDateSizeTotAreaStates1Delaware07DEC17871955195512Pennsylvania12DEC1787448204677523NewJersey18DEC178774185419334Georgia02JAN17885791811211145Connecticut09JAN1788484511695656Massachusetts06FEB1788783812479467Maryland28APR1788977513456978SouthCarolina23MAY1788301111646808 3.2AccumulatingTotalsforaGroupofData3-173.2AccumulatingTotalsforaGroupofDataObjectives¢DefineFirst.andLast.processing.¢Calculateanaccumulatingtotalforgroupsofdata.¢UseasubsettingIFstatementtooutputselectedobservations.30AccumulatingTotalsforGroupsEmpIDSalaryDivTheSASdatasetprog2.empsalsE0000442000HUMREScontainseachemployee’sE0000934000FINACEidentificationnumberE0001127000FLTOPS(EmpID),salaryE0003620000FINACE(Salary),anddivisionE0003719000FINACE(Div).ThereisoneE0004819000FLTOPSE0007727000APTOPSobservationforeachE0009720000APTOPSemployee.E0010731000FINACEE0012320000APTOPSE0015527000APTOPSE0017144000SALES31 3-18Chapter3SummarizingDataDesiredOutputHumanresourceswantsanewdatasetthatshowsthetotalsalarypaidforeachdivision.DivDivSalAPTOPS410000FINACE163000FLTOPS318000HUMRES181000SALES37300032GroupingtheDataAYoumustgroupthedataintheSASdatasetbeforeByoucanperformprocessing.EDC33 3.2AccumulatingTotalsforaGroupofData3-19ReviewoftheSORTProcedureYoucanrearrangetheobservationsintogroupsusingtheSORTprocedure.GeneralformofaPROCSORTstep:PROCSORTPROCSORTDATA=DATA=input-SAS-data-setinput-SAS-data-setoutput-SAS-data-set>;;BYBY<>BY-variable...BY-variable...;;RUN;RUN;34TheSORTProcedureTheSORTprocedure¢rearrangestheobservationsinaDATAset¢cansortonmultiplevariables¢createsaSASdatasetthatisasortedcopyoftheinputSASdataset¢replacestheinputdatasetbydefault.35 3-20Chapter3SummarizingDataSortingbyDivprocsortdata=prog2.empsalsout=salsort;byDiv;run;36ProcessingDatainGroupsDivSalaryDivSalAPTOPS20000APTOPS100000170000APTOPS50000FINACE25000FINACE20000FINACE2300095000FINACE27000SALES10000SALES120002200037 3.2AccumulatingTotalsforaGroupofData3-21BY-GroupProcessingGeneralformofaBYstatementusedwiththeSETstatement:DATADATAoutput-SAS-data-setoutput-SAS-data-set;;SETSETinput-SAS-data-setinput-SAS-data-set;;BYBYBY-variable…BY-variable…;;RUN;RUN;TheBYstatementintheDATAstepenablesyoutoprocessyourdataingroups.38WhenaBYstatementisusedwithaSETstatement,thedatamust•besortedorgroupedinorderbytheBYvariable(s),or•haveanindexbasedontheBYvariable(s),or•resideinaDBMStable.BY-GroupProcessingdatadivsals(keep=DivDivSal);setsalsort;byDiv;run;39 3-22Chapter3SummarizingDataBY-GroupProcessingABYstatementinaDATAstepcreatestemporaryvariablesforeachvariablelistedintheBYstatement.GeneralformofthenamesofBYvariablesinaDATAstep:FirstFirst..BY-variableBY-variableLastLast..BY-variableBY-variable40First.andLast.Values¢TheFirst.variablehasavalueof1forthefirstobservationinaBYgroup;otherwise,itequals0.¢TheLast.variablehasavalueof1forthelastobservationinaBYgroup;otherwise,itequals0.Usethesetemporaryvariablestoconditionallyprocesssorted,grouped,orindexeddata.41 3.2AccumulatingTotalsforaGroupofData3-23First./Last.ExampleDivSalaryFirst.DivAPTOPS200001APTOPS100000APTOPS50000Last.DivFINACE25000?FINACE20000FINACE23000FINACE27000SALES10000SALES1200042...First./Last.ExampleLookaheadDivSalaryFirst.DivAPTOPS200001APTOPS100000APTOPS50000Last.DivFINACE250000FINACE20000FINACE23000FINACE27000SALES10000SALES1200043... 3-24Chapter3SummarizingDataFirst./Last.ExampleDivSalaryFirst.DivAPTOPS200000APTOPS100000APTOPS50000Last.DivFINACE250000FINACE20000FINACE23000FINACE27000SALES10000SALES1200044...First./Last.ExampleDivSalaryFirst.DivAPTOPS200000APTOPS100000APTOPS50000Last.DivFINACE250001FINACE20000FINACE23000FINACE27000SALES10000SALES1200045... 3.2AccumulatingTotalsforaGroupofData3-25First./Last.ExampleDivSalaryFirst.DivAPTOPS200001APTOPS100000APTOPS50000Last.DivFINACE250000FINACE20000FINACE23000FINACE27000SALES10000SALES1200046WhatMustHappenWhen?Thereisathree-stepprocessforaccumulatingtotals.1.SettheaccumulatingvariabletozeroatthestartofeachBYgroup.2.Incrementtheaccumulatingvariablewithasumstatement(automaticallyretains).3.OutputonlythelastobservationofeachBYgroup.47 3-26Chapter3SummarizingDataAccumulatingTotalsforGroups1.SettheaccumulatingvariabletozeroatthestartofeachBYgroup.datadivsals(keep=DivDivSal);setsalsort;byDiv;ifFirst.DivthenDivSal=0;run;48AccumulatingTotalsforGroups2.Incrementtheaccumulatingvariablewithasumstatement(automaticallyretains).datadivsals(keep=DivDivSal);setsalsort;byDiv;ifFirst.DivthenDivSal=0;DivSal+Salary;run;49 3.2AccumulatingTotalsforaGroupofData3-27First./Last.ExampleDivSalaryDivSalAPTOPS2000020000APTOPS100000120000APTOPS50000170000FINACE2500025000FINACE2000045000FINACE2300068000FINACE2700095000SALES1000010000SALES120002200050SubsettingIFStatementThesubsettingIFdefinesaconditionthattheobservationmustmeettobefurtherprocessedbytheDATAstep.GeneralformofthesubsettingIFstatement:IFIFexpressionexpression;;¢Iftheexpressionistrue,theDATAstepcontinuesprocessingthecurrentobservation.¢Iftheexpressionisfalse,SASreturnstothetopoftheDATAstep.51 3-28Chapter3SummarizingDataAccumulatingTotalsforGroups3.OutputonlythelastobservationofeachBYgroup.datadivsals(keep=DivDivSal);setsalsort;byDiv;ifFirst.DivthenDivSal=0;DivSal+Salary;ifLast.Div;run;52!ThestatementifLast.BY-variable;meansifLast.BY-variableistrue.Anumericvalueisconsideredtrueifitisnotequaltozeroandnotmissing.SubsettingIFStatementInitializePDVInitializePDVExecuteprogramExecuteprogramstatementsstatementsNoifexpression;TrueExecuteadditionalYesExecuteadditionalprogramstatementsprogramstatementsOutputobservationOutputobservationtoSASdatasettoSASdataset53 3.2AccumulatingTotalsforaGroupofData3-29AccumulatingTotalsforGroupsPartialLogNOTE:Therewere39observationsreadfromthedatasetWORK.SALSORT.NOTE:ThedatasetWORK.DIVSALShas5observationsand2variables.54AccumulatingTotalsforGroupsprocprintdata=divsalsnoobs;run;PROCPRINTOutputDivDivSalAPTOPS410000FINACE163000FLTOPS318000HUMRES181000SALES37300055c03s2d1.sas 3-30Chapter3SummarizingDataInputDataEmpIDSalaryRegionDivTheSASdatasetprog2.regsalsE0000442000EHUMREScontainseachE0000934000WFINACEE0001127000WFLTOPSemployee’sIDnumberE0003620000WFINACE(EmpID),salaryE0003719000EFINACE(Salary),regionE0007727000CAPTOPS(Region),anddivisionE0009720000EAPTOPSE0010731000EFINACE(Div).ThereisoneE0012320000NCAPTOPSobservationforeachE0015527000WAPTOPSemployee.E0017144000WSALESE0018837000WHUMRESE0019643000CAPTOPSE0021031000EAPTOPSE00222250000NCSALESE0023641000WAPTOPS56DesiredOutputHumanResourceswantsanewdatasetthatshowsthetotalsalarypaidandthetotalnumberofemployeesforeachdivisionineachregion.PartialOutputNumRegionDivDivSalEmpsCAPTOPS700002EAPTOPS830003EFINACE1090004EFLTOPS1220003EHUMRES1780005NCAPTOPS370002NCFLTOPS28000157 3.2AccumulatingTotalsforaGroupofData3-31SortingbyRegionandDivThedatamustbesortedbyRegionandDiv.Regionistheprimarysortvariable.Divisthesecondarysortvariable.procsortdata=prog2.regsalsout=regsort;byRegionDiv;run;58SortingbyRegionandDivprocprintdata=regsortnoobs;varRegionDivSalary;run;PartialPROCPRINTOutputRegionDivSalaryCAPTOPS27000CAPTOPS43000EAPTOPS20000EAPTOPS31000EAPTOPS32000EFINACE19000EFINACE3100059 3-32Chapter3SummarizingDataMultipleBYVariablesdataregdivsals;setregsort;byRegionDiv;additionalSASstatementsrun;60MultipleBYVariables:ExampleRegionDivFirst.RegionCAPTOPS1CAPTOPSCAPTOPSFirst.DivEAPTOPS1EFINACEEFINACELast.RegionNCFINACE?NCSALESNCSALESNCSALESLast.DivNCSALES?61... 3.2AccumulatingTotalsforaGroupofData3-33MultipleBYVariables:ExampleLookaheadRegionDivFirst.RegionCAPTOPS1CAPTOPSCAPTOPSFirst.DivEAPTOPS1EFINACEEFINACELast.RegionNCFINACE0NCSALESNCSALESNCSALESLast.DivNCSALES062...MultipleBYVariables:ExampleRegionDivFirst.RegionCAPTOPS0CAPTOPSCAPTOPSFirst.DivEAPTOPS0EFINACEEFINACELast.RegionNCFINACE0NCSALESNCSALESNCSALESLast.DivNCSALES063... 3-34Chapter3SummarizingDataMultipleBYVariables:ExampleRegionDivFirst.RegionCAPTOPS0CAPTOPSCAPTOPSFirst.DivEAPTOPS0EFINACEEFINACELast.RegionNCFINACE1NCSALESNCSALESNCSALESLast.DivNCSALES164...MultipleBYVariables:ExampleRegionDivFirst.RegionCAPTOPS1CAPTOPSCAPTOPSFirst.DivEAPTOPS1EFINACEEFINACELast.RegionNCFINACE0NCSALESNCSALESNCSALESLast.DivNCSALES165... 3.2AccumulatingTotalsforaGroupofData3-35MultipleBYVariables:ExampleRegionDivFirst.RegionCAPTOPS0CAPTOPSCAPTOPSFirst.DivEAPTOPS1EFINACEEFINACELast.RegionNCFINACE0NCSALESNCSALESNCSALESLast.DivNCSALES066MultipleBYVariablesWhenyouusemorethanonevariableintheBYstatement,achangeintheprimaryvariableforcesLast.BY-variable=1forthesecondaryvariable.First.Last.First.RegionDivRegionRegionDivLast.DivCAPTOPS1010CAPTOPS0000CAPTOPS0101EAPTOPS1011EFINACE001067 3-36Chapter3SummarizingDataMultipleBYVariablesdataregdivsals(keep=RegionDivDivSalNumEmps);setregsort;byRegionDiv;ifFirst.Divthendo;DivSal=0;NumEmps=0;end;DivSal+Salary;NumEmps+1;ifLast.Div;run;68MultipleBYVariablesPartialLogNOTE:Therewere39observationsreadfromthedatasetWORK.REGSORT.NOTE:ThedatasetWORK.REGDIVSALShas14observationsand4variables.69 3.2AccumulatingTotalsforaGroupofData3-37MultipleBYVariablesprocprintdata=regdivsalsnoobs;run;PartialPROCPRINTOutputNumRegionDivDivSalEmpsCAPTOPS700002EAPTOPS830003EFINACE1090004EFLTOPS1220003c03s2d2.sas70 3-38Chapter3SummarizingDataExercises2.AccumulatingTotalsforaGroupofDataThedatasetprog2.flymileshasoneobservationforeachtripthatafrequentflyermadewithanairline.Itshowsthefrequentflyernumber(ID)andthenumberofmilesearnedforthattrip(Miles).PartialListingofprog2.flymilesIDMilesF212763F161272F31351800F25122733F25122859F31351437F313511553F31351312F1612245!ThedatasetisnotsortedbyID.Createadatasetnamedwork.freqmilesthathasoneobservationforeachfrequentflyeraswellasanewvariablenamedTotMiles,whichshowsthetotalnumberoffrequentflyermilesthepersonearned.Listingofwork.freqmilesTotObsIDMiles1F16158132F21264543F25122102084F313515090 3.2AccumulatingTotalsforaGroupofData3-393.AccumulatingTotalsforGroupsofDataUsingMorethanOneBYVariableThedatasetprog2.flydayshasoneobservationforeachtripthatafrequentflyermadewithanairline.Itcontainsthefrequentflyernumber(ID),thenumberofmilesearnedforthattrip(Miles),andavariablethatindicateswhetherthemileswereearnedonaweekdayflight(Code='MF')oraweekendflight(Code='SS').PartialListingofprog2.flydaysIDCodeMilesF212SS763F161MF272F31351SS800F25122SS733F25122MF859F31351SS437F31351SS1553F31351MF312F161SS2245CreateaSASdatasetnamedwork.daymilesthatshowshowmanytotalmileseachfrequentflyerearnedforeachtypeofflight.Listingofwork.daymilesTotObsIDCodeMiles1F161MF26332F161SS31803F212MF9764F212SS54785F25122MF70076F25122SS32017F31351MF21008F31351SS2990 3-40Chapter3SummarizingData4.DetectingDuplicateObservationsUsingBY-GroupProcessing(Optional)Thedatasetprog2.dupsalshasthevariablesEmpIDandSalary.PartialListingofprog2.dupsalsEmpIDSalaryE0029037000E0037925000E0003719000E0003727526E0023641000E0023659978E0037236000E0037241011E0042131000E0042417000Thedatasetshouldcontainonlyoneobservationperemployee(thatis,allemployeeIDnumbersshouldbeunique).However,aSASprogrammerdiscoveredsomeduplicateobservations.WriteaDATAstepthatsendsallobservationsthatarenotuniqueonEmpIDtoadatasetnamedwork.baddata,andalluniqueobservationstoadatasetnamedwork.gooddata.PartialListingofwork.gooddataNon-DuplicateEmpIDsObsEmpIDSalary1E00048190002E00077270003E00107310004E00123200005E00155270006E00188370007E00196430008E00210310009E002593200010E002722200011E002903700012E003792500013E003882500014E004213100015E004241700016E0042727000 3.2AccumulatingTotalsforaGroupofData3-41PartialListingofwork.baddataDuplicateEmpIDsObsEmpIDSalary1E00004420002E00004629023E00009340004E00009497615E00011270006E00011381937E00036200008E00036270579E000371900010E000372752611E0009720000Hint:Tocreatetwodatasets,listbothintheDATAstatement.Tocontroltowhichdatasetanobservationiswritten,usetheOUTPUTstatement.(RefertoChapter2,“ControllingInputandOutput.”) 3-42Chapter3SummarizingData5.RotatingaDataSet(Optional)Abookstoresellsthreetypesofproducts:books,cards,andperiodicals.TheSASdatasetprog2.salesbydayhasanobservationforeachproducteachdaythatthestoreisopen(threeobservationsforeachday).ThevariableSalesshowsthetotalsalesforthatproductoneachday.Partiallistingofprog2.salesbydayDateMerchTypeSales01APR2001Books1602.2701APR2001Cards669.4901APR2001Periodicals1651.4902APR2001Books2818.3302APR2001Cards217.1902APR2001Periodicals87.6203APR2001Books751.6703APR2001Cards125.7803APR2001Periodicals72.20!ThevariableDateisaSASdate,butithasapermanentDATE9.formatapplied.ThedatasetisalreadysortedbyDate.Rotatethedatasetsothatithasonlyoneobservationperday,andavariableforeachtypeofmerchandise.Thevalueforeachmerchandisetypeshouldbethesalesforthatproductonthatday.PartialOutputObsDateBooksCardsPeriodicals101APR20011602.27669.491651.49202APR20012818.33217.1987.62303APR2001751.67125.7872.20404APR2001890.872370.92587.84505APR20011926.04165.25265.96606APR2001141.111739.463725.15707APR20011406.71117.76706.78808APR2001153.1878.77171.64 3.3SolutionstoExercises3-433.3SolutionstoExercises1.CreatinganAccumulatingTotalVariabledatausarea;setprog2.states;TotArea+Size;NumStates+1;/*SumstatementscreateTotAreaandNumStates,retain,setinitialvaluesto0,andignoremissingvaluesofsize*/run;procprintdata=usarea;run;2.AccumulatingTotalsforaGroupofData/*DatamustbesortedorindexedforBY-groupprocessing*/procsortdata=prog2.flymilesout=milesort;byID;run;datafreqmiles(drop=miles);setmilesort;byID;/*BYstatementcreateFirst.IDandLast.ID*/ifFirst.IDthenTotMiles=0;/*SetTotMilesto0whenIDchanges*/TotMiles+Miles;/*SumstatementcreatesTotMiles,retainsit,setsinitialvalueto0,andignoresmissingvaluesofmiles*/ifLast.ID;/*OutputonlythelastofeachBYgroup*/run;/*Createalistreportofthedatasettoverifytheoutput*/procprintdata=freqmiles;run; 3-44Chapter3SummarizingData3.AccumulatingTotalsforaGroupofDataUsingMorethanOneBYVariable/*DatamustbesortedorindexedforBY-groupprocessing*/procsortdata=prog2.flydaysout=daysort;byIDCode;run;datadaymiles(drop=Miles);setdaysort;byIDCode;/*BYstatementcreatesFirst.ID,Last.IDFirst.Code,andLast.Code*/ifFirst.CodethenTotMiles=0;/*SetTotMilesto0whensubgroupchanges*/TotMiles+Miles;/*SumstatementcreatesTotMiles,retainsit,setsinitialvalueto0,andignoresmissingvaluesofmiles*/ifLast.Codethenoutput;/*OutputonlythelastofeachBYgroup*/run;/*Createalistreportofthedatasettoverifytheoutput*/procprintdata=daymiles;run; 3.3SolutionstoExercises3-454.DetectingDuplicateObservationsUsingBY-GroupProcessing(Optional)/*DatamustbesortedorindexedforBY-groupprocessing*/procsortdata=prog2.dupsalsout=dupsort;byEmpID;run;datagooddatabaddata;/*BothnewdatasetsmustbelistedontheDATAstatement*/setdupsort;byEmpID;/*BYstatementcreatesFirst.EmpIDandLast.EmpID*/ifFirst.EmpIDandLast.EmpID/*firstandlastofthisIDmeansit’sunique*/thenoutputgooddata;elseoutputbaddata;run;/*Createlistreportstoverifyresults*/procprintdata=gooddata;title'Non-DuplicateEmpIDs';run;procprintdata=baddata;title'DuplicateEmpIDs';run;5.RotatingaDataSet(Optional)datawidebooks(drop=MerchTypeSales);setprog2.salesbyday;bydate;retainBooksCardsPeriodicals;ifMerchType='Books'thenBooks=Sales;elseifMerchType='Cards'thenCards=Sales;elseifMerchType='Periodicals'thenPeriodicals=Sales;iflast.datethenoutput;run;procprintdata=widebooks;title'RotatingaDataSet';run; 3-46Chapter3SummarizingData Chapter4ReadingandWritingDifferentTypesofData4.1ReadingDelimitedRawDataFiles................................................................................4-34.2ControllingwhenaRecordLoads..............................................................................4-464.3ReadingHierarchicalRawDataFiles..........................................................................4-884.4SolutionstoExercises...............................................................................................4-154 4-2Chapter4ReadingandWritingDifferentTypesofData 4.1ReadingDelimitedRawDataFiles4-34.1ReadingDelimitedRawDataFilesObjectives¢Readaspace-delimitedrawdatafile.¢Readacomma-delimitedrawdatafile.¢Readarawdatafilewithmissingdataattheendofarow.¢Readarawdatafilewithmissingdatarepresentedbyconsecutivedelimiters.3ListInputwiththeDefaultDelimiter500014feb19891325305000211nov19891525405000322oct199190530500044feb19931725505000524jun19931705105000620dec1994180520¢Thedataisnotinfixedcolumns.¢Thefieldsareseparatedbyspaces.¢Thereisonenonstandardfield.4 4-4Chapter4ReadingandWritingDifferentTypesofDataListInputRawdatawithfieldsthatarenotinfixedcolumnsiscalledfreeformat.Uselistinputtoreadfree-formatdata.ThelistinputstylesignalstotheSASSystemthatfieldsareseparatedbydelimiters.SASthenreadsfromnon-delimitertodelimiterinsteadoffromaspecificlocationontherawdatarecord.5DelimitersCommondelimitersareblankscommastabcharactersAspace(blank)isthedefaultdelimiter.6 4.1ReadingDelimitedRawDataFiles4-5ListInputGeneralformoftheINPUTstatementforlistinput:INPUTINPUTvar-1var-1$$var-2var-2......var-nvar-n;;Youmustspecifythevariablesintheorderthattheyappearintherawdatafile.Specifya$afterthevariablenameifitischaracter.Nosymbolafterthevariablenameindicatesanumericvariable.7InputDataThesecondfieldisadate.HowdoesSASstoredatevalues?500014feb19891325305000211nov19891525405000322oct199190530500044feb19931725505000524jun19931705105000620dec19941805208 4-6Chapter4ReadingandWritingDifferentTypesofDataStandardDataThetermstandarddatareferstocharacterandnumericdatathatSASrecognizesautomatically.Examplesofstandardnumericdata:¢35469.93¢3E5(exponentialnotation)¢-46859Standardcharacterdataisanycharacteryoucantypeonyourkeyboard.Standardcharactervaluesarealwaysleft-justifiedbySAS.9Thefollowingaretheonlyacceptablecharactersinastandardnumericfield:0123456789.EeDd-+!E,e,D,anddrepresentexponentialnotationinastandardnumericfield.Forexample,3E5isanalternativewayofwriting300000. 4.1ReadingDelimitedRawDataFiles4-7NonstandardDataThetermnonstandarddatareferstocharacterandnumericdatathatSASdoesnotrecognizeautomatically.Examplesofnonstandardnumericdata:¢12/12/2012¢29FEB2000¢4,242¢$89,00010Examplesofnonstandardcharacterdataincludepreservingleadingblanksincharactervalues,hexadecimalcharacters,andvaluessurroundedbymatchingquotes. 4-8Chapter4ReadingandWritingDifferentTypesofDataInformatsToreadnonstandarddata,youmustapplyaninformat.Generalformofaninformat:<<$$>>INFORMAT-NAMEINFORMAT-NAME.<.

>InformatsareinstructionsthatspecifyhowSASreadsrawdata.11$indicatesacharacterinformat.INFORMAT-NAMEisthenameoftheinformat.wisanoptionalfieldwidth.Ifnowidthisspecified,SASusesthedefaultwidthforthatinformat..istherequireddelimiter.disanoptionaldecimalspecificationfornumericinformats. 4.1ReadingDelimitedRawDataFiles4-9InformatsExamplesofinformatsareCOMMAw.readsnumericdata($4,242)andstripsoutselectednonnumericcharacters,suchasdollarsignsandcommas.MMDDYYw.readsdatesintheform12/31/2012.DATEw.readsdatesintheform29Feb2000.12Withdateinformats,SASusesthespecifiedwidthtodeterminehowfartoread.Withthelistinputstyle,thelengthoftheinformatisnotimportantbecausethedelimiterdetermineshowfarSASreads.Withdateformats,thespecifiedwidthdetermines•whetherSASdisplaysatwo-orfour-digityear•whetherSASdisplaysdividersiftheyarevalidforthatformat.SpecifyinganInformatTospecifyaninformatwhenusinglistinput,usethecolon(:)formatmodifierintheINPUTstatementbetweenthevariablenameandtheinformat.GeneralformofaformatmodifierinanINPUTstatement:INPUTINPUTvariablevariable::informatinformat;;13 4-10Chapter4ReadingandWritingDifferentTypesofDataWithouttheColonThecolonsignalsthatSASshouldreadfromnon-delimitertodelimiter.Ifthecolonisomitted,SASreadsthewidthoftheinformat,whichmightcauseittoreadpasttheendofthefieldortostopreadingbeforetheendofthefield.¢Noerrormessageisprinted.¢Youmightseeinvaliddatamessagesorunexpecteddatavalues.14Example:Supposethatyouhavethefollowingdatarecord:Cheema,3May1975,FandtheprogrammerforgotthecolonintheINPUTstatement,asfollows:datanew;infile'birthdays.dat'dlm=',';inputName$Birthdaydate9.Gender$;run;ForBirthday,SASreadsexactlyninecharacters,startingatthefirstpositionoftheDatefield.Thisresultsinthefollowingvalue:3May1975,Commasarenotvalidinadatefield.WhenSASattemptstoconvertthisvaluetoaSASdatevalue,itprintsaninvaliddatamessagetothelogandsetsthevalueofBirthdaytomissing. 4.1ReadingDelimitedRawDataFiles4-11ReadingaDelimitedRawDataFiledataairplanes;infile'raw-data-file';inputID$InService:date9.PassCapCargoCap;run;HowdoesSASdeterminethelengthsofthesevariables?15LengthsofVariablesWhenyouuselistinput,thedefaultlengthforcharacterandnumericvariablesiseightbytes.YoucansetthelengthofvariableswithaLENGTHstatementorwithaninformat.GeneralformofaLENGTHstatement:LENGTHLENGTHvariable-name(s)variable-name(s)<$><$>length-specification...length-specification...;;16Youdonotneedtosetthelengthsofnumericvariableswhenreadingwithlistinputbecausethedefaultwidthofeightbytesissufficient.Youcannotstoreanumericinmorethaneightbytes.Storinganumericinlessthaneightbytesreducesitsprecisionandcancauseunexpectedresults. 4-12Chapter4ReadingandWritingDifferentTypesofDataSettingtheLengthofaVariabledataairplanes;lengthID$5;infile'raw-data-file';inputID$InService:date9.PassCapCargoCap;run;c04s1d1.sas17Aninformatcanalsosetthelengthofacharactervariable.Thefollowingcodeproducesthesameresultasthecodeusedintheexample:dataairplanes;infile'raw-data-file';inputID:$5.InService:date9.PassCapCargoCap;run;!Ifyouusethismethodtosetthelengthsofcharactervariables,becertaintousethecolonmodifier. 4.1ReadingDelimitedRawDataFiles4-13UsingListInput:Compilationdataairplanes;lengthID$5;infile'raw-data-file';inputID$InService:date9.PassCapCargoCap;run;InputBufferPDVID$518...UsingListInput:Compilationdataairplanes;lengthID$5;infile'raw-data-file';inputID$InService:date9.PassCapCargoCap;run;InputBufferPDVIDInServicePassCapCargoCap$5N8N8N819... 4-14Chapter4ReadingandWritingDifferentTypesofDataUsingListInput:ExecutionRawDataFiledataairplanes;500014feb1989132530lengthID$5;5000211nov1989152540infile'raw-data-file';5000322oct199190530inputID$500044feb1993172550InService:date9.5000524jun1993170510PassCapCargoCap;5000620dec1994180520run;InputBufferInitializePDVtomissingPDVIDInServicePassCapCargoCap$5N8N8N8...20...UsingListInput:ExecutionRawDataFiledataairplanes;500014feb1989132530lengthID$5;5000211nov1989152540infile'raw-data-file';5000322oct199190530inputID$500044feb1993172550InService:date9.5000524jun1993170510PassCapCargoCap;5000620dec1994180520run;InputBufferPDVIDInServicePassCapCargoCap$5N8N8N8...21... 4.1ReadingDelimitedRawDataFiles4-15UsingListInput:ExecutionRawDataFiledataairplanes;500014feb1989132530lengthID$5;5000211nov1989152540infile'raw-data-file';5000322oct199190530inputID$500044feb1993172550InService:date9.5000524jun1993170510PassCapCargoCap;5000620dec1994180520run;InputBuffer500014feb1989132530PDVIDInServicePassCapCargoCap$5N8N8N8...22...UsingListInput:ExecutionRawDataFiledataairplanes;500014feb1989132530lengthID$5;5000211nov1989152540infile'raw-data-file';5000322oct199190530inputID$500044feb1993172550InService:date9.5000524jun1993170510PassCapCargoCap;5000620dec1994180520run;InputBuffer500014feb1989132530PDVIDInServicePassCapCargoCap$5N8N8N8500011062713253023... 4-16Chapter4ReadingandWritingDifferentTypesofDataUsingListInput:ExecutionRawDataFiledataairplanes;500014feb1989132530lengthID$5;5000211nov1989152540infile'raw-data-file';5000322oct199190530inputID$500044feb1993172550InService:date9.5000524jun1993170510PassCapCargoCap;5000620dec1994180520run;AutomaticInputBufferAutomaticreturnoutput500014feb1989132530PDVIDInServicePassCapCargoCap$5N8N8N8500011062713253024Writeobservationtoairplanes....UsingListInput:ExecutionRawDataFiledataairplanes;500014feb1989132530lengthID$5;5000211nov1989152540infile'raw-data-file';5000322oct199190530inputID$500044feb1993172550InService:date9.5000524jun1993170510PassCapCargoCap;5000620dec1994180520run;InputBuffer500014feb1989132530ReinitializePDVtomissingPDVIDInServicePassCapCargoCap$5N8N8N8...25... 4.1ReadingDelimitedRawDataFiles4-17UsingListInput:ExecutionRawDataFiledataairplanes;500014feb1989132530lengthID$5;5000211nov1989152540infile'raw-data-file';5000322oct199190530inputID$500044feb1993172550InService:date9.5000524jun1993170510PassCapCargoCap;5000620dec1994180520run;InputBuffer500014feb1989132530PDVIDInServicePassCapCargoCap$5N8N8N8...26...UsingListInput:ExecutionRawDataFiledataairplanes;500014feb1989132530lengthID$5;5000211nov1989152540infile'raw-data-file';5000322oct199190530inputID$500044feb1993172550InService:date9.5000524jun1993170510PassCapCargoCap;5000620dec1994180520run;InputBuffer5000211nov1989152540PDVIDInServicePassCapCargoCap$5N8N8N8...27... 4-18Chapter4ReadingandWritingDifferentTypesofDataUsingListInput:ExecutionRawDataFiledataairplanes;500014feb1989132530lengthID$5;5000211nov1989152540infile'raw-data-file';5000322oct199190530inputID$500044feb1993172550InService:date9.5000524jun1993170510PassCapCargoCap;5000620dec1994180520run;InputBuffer5000211nov1989152540PDVIDInServicePassCapCargoCap$5N8N8N8500021090715254028...UsingListInput:ExecutionRawDataFiledataairplanes;500014feb1989132530lengthID$5;5000211nov1989152540infile'raw-data-file';5000322oct199190530inputID$500044feb1993172550InService:date9.5000524jun1993170510PassCapCargoCap;5000620dec1994180520run;InputBufferAutomaticreturnAutomaticoutput5000211nov1989152540PDVIDInServicePassCapCargoCap$5N8N8N8500021090715254029Writeobservationtoairplanes.... 4.1ReadingDelimitedRawDataFiles4-19UsingListInput:ExecutionRawDataFiledataairplanes;500014feb1989132530lengthID$5;5000211nov1989152540infile'raw-data-file';5000322oct199190530inputID$500044feb1993172550InService:date9.5000524jun1993170510PassCapCargoCap;5000620dec1994180520run;InputBuffer5000211nov1989152540ContinueprocessinguntilPDVendoftherawdatafileIDInServicePassCapCargoCap$5N8N8N8500021090715254030 4-20Chapter4ReadingandWritingDifferentTypesofDataReadingaRawDataFilewithListInputprocprintdata=airplanesnoobs;run;PROCPRINTOutputInPassCargoIDServiceCapCap50001106271325305000210907152540500031161790530500041208817255050005122281705105000612772180520c04s1d1.sas31!InServiceappearsasaSASdate,thatis,thenumberofdayssinceJanuary1,1960.Tochangethedate’sappearance,applyaSASdateformatwithaFORMATstatementinthePRINTprocedure.YoucanalsouseaFORMATstatementintheDATAsteptopermanentlyassociateaformatwithavariable.Non-DefaultDelimiterThefieldsareseparatedbycommas.50001,4feb1989,132,53050002,11nov1989,152,54050003,22oct1991,90,53050004,4feb1993,172,55050005,24jun1993,170,51050006,20dec1994,180,52032 4.1ReadingDelimitedRawDataFiles4-21UsingtheDLM=OptionTheDLM=optionsetsacharacterorcharactersthatSASrecognizesasadelimiterintherawdatafile.GeneralformoftheINFILEstatementwiththeDLM=option:INFILEINFILE'raw-data-file'raw-data-file'DLM=''DLM='delimiter(s)delimiter(s)';';Anycharacteryoucantypeonyourkeyboardcanbeadelimiter.Youcanalsousehexadecimalcharacters.33IfyouspecifymorethanonedelimiterintheDLM=option,anyofthosecharactersisrecognizedasadelimiter.Forexample,DLM=',!'indicatesthateitheracommaoranexclamationpointactsasadelimiter.Bydefault,twoormoreconsecutivedelimitersaretreatedasone;therefore,acommaandanexclamationpointtogetherarealsotreatedasadelimiter.Oneexampleofahexadecimalcharacterisatabcharacter.TospecifyatabcharacteronaPCoronUNIX,typedlm='09'x.Tospecifyatabcharacteronz/OS,typedlm='05'x.!YoucanfindthehexadecimalrepresentationofaprintablecharacterusingtheHEXw.or$HEXw.formatinSAS.Fornonprintablecharacterslikeatabcharacter,youshouldconsultaprogrammingreferenceforyouroperatingsystem. 4-22Chapter4ReadingandWritingDifferentTypesofDataSpecifyingaDelimiterdataairplanes2;lengthID$5;infile'raw-data-file'dlm=',';inputID$InService:date9.PassCapCargoCap;run;c04s1d1.sas34MissingDataattheEndofaRow50001,4feb1989,13250002,11nov1989,152,54050003,22oct1991,90,53050004,4feb1993,17250005,24jun1993,170,51050006,20dec1994,180,52035 4.1ReadingDelimitedRawDataFiles4-23MissingDataattheEndofaRowBydefault,whenthereismissingdataattheendofarow,thefollowingoccurs:1.SASloadsthenextrecordtofinishtheobservation.2.Anoteiswrittentothelog.36MissingDataattheEndofaRow:Executiondataairplanes3;RawDataFilelengthID$5;50001,4feb1989,132infile'raw-data-file'50002,11nov1989,152,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172InService:date9.50005,24jun1993,170,510PassCapCargoCap;50006,20dec1994,180,520run;InputBufferInitializePDVtomissingPDVIDInServicePassCapCargoCap$5N8N8N8...37... 4-24Chapter4ReadingandWritingDifferentTypesofDataMissingDataattheEndofaRow:Executiondataairplanes3;RawDataFilelengthID$5;50001,4feb1989,132infile'raw-data-file'50002,11nov1989,152,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172InService:date9.50005,24jun1993,170,510PassCapCargoCap;50006,20dec1994,180,520run;InputBufferPDVIDInServicePassCapCargoCap$5N8N8N8...38...MissingDataattheEndofaRow:Executiondataairplanes3;RawDataFilelengthID$5;50001,4feb1989,132infile'raw-data-file'50002,11nov1989,152,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172InService:date9.50005,24jun1993,170,510PassCapCargoCap;50006,20dec1994,180,520run;InputBuffer50001,4feb1989,132PDVIDInServicePassCapCargoCap$5N8N8N8...39... 4.1ReadingDelimitedRawDataFiles4-25MissingDataattheEndofaRow:Executiondataairplanes3;RawDataFilelengthID$5;50001,4feb1989,132infile'raw-data-file'50002,11nov1989,152,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172InService:date9.50005,24jun1993,170,510PassCapCargoCap;50006,20dec1994,180,520run;InputBuffer50001,4feb1989,132NodataPDVIDInServicePassCapCargoCap$5N8N8N85000110627132.40...MissingDataattheEndofaRow:Executiondataairplanes3;RawDataFilelengthID$5;50001,4feb1989,132infile'raw-data-file'50002,11nov1989,152,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172InService:date9.50005,24jun1993,170,510PassCapCargoCap;50006,20dec1994,180,520run;InputBuffer50002,11nov1989,152,540SASloadsPDVIDInServicePassCapCargoCapnextrecord$5N8N8N850001106271325000241... 4-26Chapter4ReadingandWritingDifferentTypesofDataMissingDataattheEndofaRow:Executiondataairplanes3;RawDataFilelengthID$5;50001,4feb1989,132infile'raw-data-file'50002,11nov1989,152,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172InService:date9.50005,24jun1993,170,510PassCapCargoCap;50006,20dec1994,180,520run;InputBufferAutomaticreturnAutomaticoutput50002,11nov1989,152,540PDVIDInServicePassCapCargoCap$5N8N8N850001106271325000242Writeobservationtoairplanes3....MissingDataattheEndofaRow:Executiondataairplanes3;RawDataFilelengthID$5;50001,4feb1989,132infile'raw-data-file'50002,11nov1989,152,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172InService:date9.50005,24jun1993,170,510PassCapCargoCap;50006,20dec1994,180,520run;InputBuffer50002,11nov1989,152,540ReinitializePDVtomissingPDVIDInServicePassCapCargoCap$5N8N8N8....43... 4.1ReadingDelimitedRawDataFiles4-27MissingDataattheEndofaRow:Executiondataairplanes3;RawDataFilelengthID$5;50001,4feb1989,132infile'raw-data-file'50002,11nov1989,152,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172InService:date9.50005,24jun1993,170,510PassCapCargoCap;50006,20dec1994,180,520run;InputBuffer50001,4feb1989,132PDVIDInServicePassCapCargoCap$5N8N8N8....44...MissingDataattheEndofaRow:Executiondataairplanes3;RawDataFilelengthID$5;50001,4feb1989,132infile'raw-data-file'50002,11nov1989,152,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172InService:date9.50005,24jun1993,170,510PassCapCargoCap;50006,20dec1994,180,520run;InputBuffer50003,22oct1991,90,530PDVIDInServicePassCapCargoCap$5N8N8N8...45... 4-28Chapter4ReadingandWritingDifferentTypesofDataMissingDataattheEndofaRow:Executiondataairplanes3;RawDataFilelengthID$5;50001,4feb1989,132infile'raw-data-file'50002,11nov1989,152,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172InService:date9.50005,24jun1993,170,510PassCapCargoCap;50006,20dec1994,180,520run;InputBuffer50003,22oov1989,152,540ContinueprocessinguntilendoftherawdatafilePDVIDInServicePassCapCargoCap$5N8N8N850003116179053046PartialSASLogNOTE:6recordswerereadfromtheinfile'aircraft3.dat'.Theminimumrecordlengthwas19.Themaximumrecordlengthwas26.NOTE:SASwenttoanewlinewhenINPUTstatementreachedpasttheendofaline.NOTE:ThedatasetWORK.AIRPLANES3has4observationsand4variables.47 4.1ReadingDelimitedRawDataFiles4-29MissingDataattheEndoftheRowprocprintdata=airplanes3noobs;run;PROCPRINTOutputInPassCargoIDServiceCapCap500011062713250002500031161790530500041208817250005500061277218052048TheMISSOVEROptionTheMISSOVERoptionpreventsSASfromloadinganewrecordwhentheendofthecurrentrecordisreached.GeneralformoftheINFILEstatementwiththeMISSOVERoption:INFILEINFILE'raw-data-file''raw-data-file'MISSOVERMISSOVER;;IfSASreachestheendoftherowwithoutfindingvaluesforallfields,variableswithoutvaluesaresettomissing.49 4-30Chapter4ReadingandWritingDifferentTypesofDataUsingtheMISSOVEROptiondataairplanes3;lengthID$5;infile'raw-data-file'dlm=','missover;inputID$InService:date9.PassCapCargoCap;run;c04s1d1.sas50UsingtheMISSOVEROptionPartialSASLogNOTE:6recordswerereadfromtheinfile'aircraft3.dat'.Theminimumrecordlengthwas19.Themaximumrecordlengthwas26.NOTE:ThedatasetWORK.AIRPLANES3has6observationsand4variables.51 4.1ReadingDelimitedRawDataFiles4-31UsingtheMISSOVEROptionprocprintdata=airplanes3noobs;run;PROCPRINTOutputInPassCargoIDServiceCapCap5000110627132.50002109071525405000311617905305000412088172.50005122281705105000612772180520c04s1d1.sas52TheMISSOVERoptionisalsovalidinformattedandcolumninputandcanbeusedwhenyouwanttoensurethatincompletefieldsaresettomissing.Supposethereisarawdatafilewiththefollowingvalues:122333Iftheshorterrecordsarenotpaddedwithblanks,readingthefilewiththefollowingcodeproducesallmissingvalues:datanums;infile'raw-data-file'missover;inputnum4.;run;Noticetheinformat.ThisspecifiesthatSASistolookforexactlyfourbytesofdata.Inthiscase,theMISSOVERoptionindicatesthevariableistobesettomissingifthefieldisthreebytesorless.TheTRUNCOVERoptionenablesSAStoreadvariable-lengthrecordswithoutsettingincompletefieldstomissing.Ifthesamerawdatafileisreadwiththecodedatanums;infile'raw-data-file'truncover;inputnum4.;run;theresultingvaluesare1,22,333.Whenusedwithlistinputandwithoutinformats,theMISSOVERandTRUNCOVERoptionsproducethesameresults. 4-32Chapter4ReadingandWritingDifferentTypesofDataAnotherINFILEstatementoptionthatdealswithvariablelengthrecordsisthePADoption.ThePADoptioninstructsSAStomakeallrecordsthesamelengthbyaddingspacestotheendofshorterrecords.AllrecordsarepaddedtoeitherthedefaultrecordlengthortherecordlengthspecifiedbytheLRECL=option.ItisoftenusedintheWindowsoperatingenvironmentwithcolumnorformattedinputtopreventcarriagereturnsfromaffectinghowrawdataisread.ThePADoptionisnotappropriateforreadingdelimitedfileswithlistinputbecauseitcancauseunexpectedresults.Thisisespeciallytrueifthedataisdelimitedwithspacesorifthereispotentiallymorethanonemissingfieldattheendofsomerows.MissingValueswithoutaPlaceholderThereismissingdatarepresentedbytwoconsecutivedelimiters.50001,4feb1989,,53050002,11nov1989,132,54050003,22oct1991,90,53050004,4feb1993,172,55050005,24jun1993,,51050006,20dec1994,180,52053 4.1ReadingDelimitedRawDataFiles4-33MissingValueswithoutaPlaceholderBydefault,SAStreatstwoconsecutivedelimitersasone.Missingdatashouldberepresentedbyaplaceholder.50001,4feb1989,.,53054Aplaceholdercanbeaperiodifthedataisnumeric,oraspaceifthedataischaracterandthefileisnotspace-delimited.MissingValueswithoutaPlaceholderdataairplanes4;lengthID$5;infile'raw-data-file'dlm=',';inputID$InService:date9.PassCapCargoCap;run;55 4-34Chapter4ReadingandWritingDifferentTypesofDataMissingValueswithoutPlaceholder:Executiondataairplanes4;RawDataFilelengthID$5;50001,4feb1989,,530infile'raw-data-file'50002,11nov1989,132,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172,550InService:date9.50005,24jun1993,,510PassCapCargoCap;50006,20dec1994,180,520run;InputBufferInitializePDVtomissingPDVIDInServicePassCapCargoCap$5N8N8N8...56...MissingValueswithoutPlaceholder:Executiondataairplanes4;RawDataFilelengthID$5;50001,4feb1989,,530infile'raw-data-file'50002,11nov1989,132,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172,550InService:date9.50005,24jun1993,,510PassCapCargoCap;50006,20dec1994,180,520run;InputBufferPDVIDInServicePassCapCargoCap$5N8N8N8...57... 4.1ReadingDelimitedRawDataFiles4-35MissingValueswithoutPlaceholder:Executiondataairplanes4;RawDataFilelengthID$5;50001,4feb1989,,530infile'raw-data-file'50002,11nov1989,132,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172,550InService:date9.50005,24jun1993,,510PassCapCargoCap;50006,20dec1994,180,520run;InputBuffer50001,4feb1989,,530PDVIDInServicePassCapCargoCap$5N8N8N8...58...MissingValueswithoutPlaceholder:Executiondataairplanes4;RawDataFilelengthID$5;50001,4feb1989,,530infile'raw-data-file'50002,11nov1989,132,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172,550InService:date9.50005,24jun1993,,510PassCapCargoCap;50006,20dec1994,180,520run;InputBuffer50001,4feb1989,,530NodataPDVIDInServicePassCapCargoCap$5N8N8N85000110627530.59... 4-36Chapter4ReadingandWritingDifferentTypesofDataMissingValueswithoutPlaceholder:Executiondataairplanes4;RawDataFilelengthID$5;50001,4feb1989,,530infile'raw-data-file'50002,11nov1989,132,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172,550InService:date9.50005,24jun1993,,510PassCapCargoCap;50006,20dec1994,180,520run;InputBuffer50002,11nov1989,132,540SASloadsPDVnextrecordIDInServicePassCapCargoCap$5N8N8N85000110627530.60...MissingValueswithoutPlaceholder:Executiondataairplanes4;RawDataFilelengthID$5;50001,4feb1989,,530infile'raw-data-file'50002,11nov1989,132,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172,550InService:date9.50005,24jun1993,,510PassCapCargoCap;50006,20dec1994,180,520run;InputBuffer50002,11nov1989,132,540PDVIDInServicePassCapCargoCap$5N8N8N850001106275305000261... 4.1ReadingDelimitedRawDataFiles4-37MissingValueswithoutPlaceholder:Executiondataairplanes4;RawDataFilelengthID$5;50001,4feb1989,,530infile'raw-data-file'50002,11nov1989,132,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172,550InService:date9.50005,24jun1993,,510PassCapCargoCap;50006,20dec1994,180,520run;InputBufferAutomaticreturnAutomaticoutput50002,11nov1989,132,540PDVIDInServicePassCapCargoCap$5N8N8N850001106275305000262Writeobservationtoairplanes4....MissingValueswithoutPlaceholder:Executiondataairplanes4;RawDataFilelengthID$5;50001,4feb1989,,530infile'raw-data-file'50002,11nov1989,132,540dlm=',';50003,22oct1991,90,530inputID$50004,4feb1993,172,550InService:date9.50005,24jun1993,,510PassCapCargoCap;50006,20dec1994,180,520run;InputBufferContinueprocessing50003,22ocv1989,132,540untilendoftherawdatafilePDVIDInServicePassCapCargoCap$5N8N8N850003116719053063 4-38Chapter4ReadingandWritingDifferentTypesofDataMissingValueswithoutaPlaceholderPartialSASLogNOTE:6recordswerereadfromtheinfile'aircraft4.dat'.Theminimumrecordlengthwas21.Themaximumrecordlengthwas26.NOTE:SASwenttoanewlinewhenINPUTstatementreachedpasttheendofaline.NOTE:ThedatasetWORK.AIRPLANES4has4observationsand4variables.64MissingValueswithoutaPlaceholderprocprintdata=airplanes4noobs;run;PROCPRINTOutputInPassCargoIDServiceCapCap500011062753050002500031161790530500041208817255050005122285105000665 4.1ReadingDelimitedRawDataFiles4-39MissingValueswithoutaPlaceholderIfyourdatadoesnothaveaplaceholder,usetheDSDoption.50001,4feb1989,,53066TheDSDOptionGeneralformoftheDSDoptionintheINFILEstatement:INFILEINFILE‘raw-data-file‘raw-data-file'DSD'DSD;;67 4-40Chapter4ReadingandWritingDifferentTypesofDataTheDSDOptionTheDSDoption¢setsthedefaultdelimitertoacomma¢treatsconsecutivedelimitersasmissingvalues¢enablesSAStoreadvalueswithembeddeddelimitersifthevalueissurroundedbymatchingquotationmarks.68Forexample,thefollowingrecordiscomma-delimited,butthesalaryvaluehasanembeddedcomma.Zoellner,Jane,"$55,000"TheDSDoptionsignalsSAStoignoredelimitersthataresurroundedbymatchingquotationmarks.UsingtheDSDOptiondataairplanes4;lengthID$5;infile'raw-data-file'dsd;inputID$InService:date9.PassCapCargoCap;run;c04s1d1.sas69 4.1ReadingDelimitedRawDataFiles4-41MissingValueswithoutaPlaceholderPartialSASLogNOTE:6recordswerereadfromtheinfile'aircraft4.dat'.Theminimumrecordlengthwas22.Themaximumrecordlengthwas25.NOTE:ThedatasetWORK.AIRPLANES4has6observationsand4variables.70UsingtheDSDOptionprocprintdata=airplanes4noobs;run;PROCPRINTOutputInPassCargoIDServiceCapCap5000110627.530500021090713254050003116179053050004120881725505000512228.5105000612772180520c04s1d1.sas71 4-42Chapter4ReadingandWritingDifferentTypesofDataINFILEStatementOptionsProblemOptionNon-blankdelimitersDLM='delimiter(s)'MissingdataatendofrowMISSOVERMissingdatarepresentedbyconsecutiveDSDdelimitersand/orEmbeddeddelimiterswherevaluesaresurroundedbymatchingquotationmarksTheseoptionscanbeusedseparatelyortogetherintheINFILEstatement.72 4.1ReadingDelimitedRawDataFiles4-43Exercises1.ReadingNonstandardDataTheSTATESrawdatafilecontainsinformationonstatename,statepopulation,statesize,anddateofstatehood.Theorderandlayoutofthefieldsareasfollows:OrderFieldNotes1StateNameLongestvalueis14characters2StatePopulationWritteninCOMMA10.3StateSizeSquaremiles(numericfield)4DateofStatehoodWritteninDATE9.SampleRecordsAlabama!4,447,100!50750!14DEC1819Alaska!626,932!570374!03JAN1959Arizona!5,130,632!113642!14FEB1912Arkansas!2,673,400!52075!15JUN1836California!33,871,648!155973!09SEP1850Colorado!4,301,261!103729!01AUG1876Connecticut!3,405,565!4845!09JAN1788UsetheSTATESrawdatafiletocreatethework.statesdatasetlistedbelow.PartialListingofwork.statesEnterObsStatePopulationSizeDate1Alabama444710050750-511522Alaska626932570374-3633Arizona5130632113642-174884Arkansas267340052075-451245California33871648155973-399256Colorado4301261103729-304677Connecticut34055654845-628138Delaware7836001955-628469Florida1598237853997-4194110Georgia818645357918-62820!ThevariableEnterDateisaSASdate,anditisdisplayedasthenumberofdayssinceJanuary1,1960bydefault.Toviewthevaluesascalendardates,applyaSASdateformat.(SeeSection1.4,“ReviewofDisplayingSASDataSets.”)YoucanapplytheformatwithaFORMATstatementineithertheDATAsteporthePROCPRINTstep. 4-44Chapter4ReadingandWritingDifferentTypesofData2.UsingINFILEStatementOptionstoChangeDefaultsTheAROMASrawdatafilecontainsinformationondifferentconditionsandpossiblearomatherapycures.Foreachrecord,theconditionislistedfirstandfollowedbyasmanyasthreepossiblecures.OrderFieldNotes1ConditionLongestvalueis11characters.2PossibleCureLongestvalueis11characters.3PossibleCureLongestvalueis11characters.4PossibleCureLongestvalueis11characters.SampleRecordsANGER"YlangYlang"ANXIETYBergamotPetitgrainBOREDOMLemongrassDEPRESSIONBasilBergamotImmortelleDULLNESSGrapefruitLemongrassLimeGRIEFMelissaHEADACHEChamomileLavenderFATIGUEBasilPeppermintRosemaryINSOMNIAChamomileLavenderMarjoram!Thefieldsareseparatedbyspaces,andonefieldhasembeddeddelimiterswithquotesaroundthevalue.Alltherecordsdonothavevaluesforallfields.UsetheAROMASrawdatafiletocreatethework.aromasdatasetlistedbelow.AromatherapyDataSetObsConditionCure1Cure2Cure31ANGERYlangYlang2ANXIETYBergamotPetitgrain3BOREDOMLemongrass4DEPRESSIONBasilBergamotImmortelle5DULLNESSGrapefruitLemongrassLime6GRIEFMelissa7HEADACHEChamomileLavender8FATIGUEBasilPeppermintRosemary9INSOMNIAChamomileLavenderMarjoram10MIGRAINELavender11STRESSBenzoinBergamotChamomile12VERTIGOLavenderPeppermint13SHOCKPeppermintPetitgrain!Thisdatasetisnotintendedasmedicaladviceorasaguidetoaromatherapy. 4.1ReadingDelimitedRawDataFiles4-453.ReadingaFixed-ColumnRawDataFilewithVariableLengthRecords(Optional)TheAROMASFrawdatafileisafixed-columnversionoftheAROMASrawdatafile.Ithasthefollowinglayout:FieldStartingPositionFieldLengthCondition110Cure11111Cure22211Cure33311SamplerecordsANGERYlangYlangANXIETYBergamotPetitgrainBOREDOMLemongrassDEPRESSIONBasilBergamotImmortelleDULLNESSGrapefruitLemongrassLimeGRIEFMelissaHEADACHEChamomileLavenderFATIGUEBasilPeppermintRosemaryINSOMNIAChamomileLavenderMarjoramMIGRAINELavenderSTRESSBenzoinBergamotChamomileVERTIGOLavenderPeppermintSHOCKPeppermintPetitgrainReadtheAROMASFrawdatafile,usingcolumnorformattedinput,andcreatethework.aromasfSASdataset.Verifythedatacarefully.YoushouldhavethesameoutputasinExercise2.!Forhelponreadingrawdatawithformattedinput,reviewChapter1,Section2.Forhelponoptionsforfixed-columnrawdatafiles,readthenotesaboutMISSOVER,TRUNCOVER,andPAD.!ThisexerciseisonlyappropriateforWindowsandUNIXusers. 4-46Chapter4ReadingandWritingDifferentTypesofData4.2ControllingwhenaRecordLoadsObjectives¢Readarawdatafilewithmultiplerecordsperobservation.¢Readarawdatafilewithmixedrecordtypes.¢Subsetfromarawdatafile.¢Readarawdatafilewithmultipleobservationsperrecord.75MultipleRecordsPerObservationFarr,SueArawdatafilehasthreeAnaheim,CArecordsperemployee.869-7008Record1containsthefirstAnderson,KayB.andlastnames,record2Chicago,ILcontainsthecityandstate483-3321ofresidence,andrecord3Tennenbaum,MaryAnncontainstheemployee’sJefferson,MOphonenumber.589-903076 4.2ControllingwhenaRecordLoads4-47DesiredOutputTheSASdatasetshouldhaveoneobservationperemployee.LNameFNameCityStatePhoneFarrSueAnaheimCA869-7008AndersonKayB.ChicagoIL483-3321TennenbaumMaryAnnJeffersonMO589-903077TheINPUTStatementTheSASSystemloadsanewrecordintotheinputbufferwhenitencountersanINPUTstatement.YoucanhavemultipleINPUTstatementsinoneDATAstep.DATADATASAS-data-setSAS-data-set;;INPUTINPUTvar-1var-2var-3var-1var-2var-3;;INPUTINPUTvar-4var-5var-4var-5;;EachINPUTstatementendswithasemicolon.78 4-48Chapter4ReadingandWritingDifferentTypesofDataMultipleINPUTStatementsdataaddress;lengthLNameFName$20City$25State$2Phone$8;infile'raw-data-file'dlm=',';LoadRecordinputLName$FName$;LoadRecordinputCity$State$;LoadRecordinputPhone$;run;81LinePointerControlsYoucanalsouselinepointercontrolstocontrolwhenSASloadsanewrecord.DATADATASAS-data-setSAS-data-set;;INPUTINPUTvar-1var-2var-3var-1var-2var-3//var-4var-5var-4var-5;;SASloadsthenextrecordwhenitencountersaforwardslash.82 4.2ControllingwhenaRecordLoads4-49ReadingMultipleRecordsperObservationdataaddress;lengthLNameFName$20City$25State$2Phone$8;infile'raw-data-file'dlm=',';LoadRecordinputLName$FName$/LoadRecordCity$State$/LoadRecordPhone$;run;85Theforwardslashisknownasarelativelinepointercontrolthatmovesthepointerrelativetothelineonwhichitcurrentlyappears.Thereisalsoanabsolutelinepointercontrolthatmovesthepointertoaspecificline.Example:dataexample;infile'raw-data-file';input#1LName$FName$#2City$State$#3Phone$;run;LNameandFNamearereadfromrecord1,CityandStatefromrecord2,andPhonefromrecord3onthefirstiterationoftheDATAstep.Then,LNameandFNamearereadfromrecord4,CityandStatefromrecord5,andPhonefromrecord6ontheseconditerationoftheDATAstep,andsoon. 4-50Chapter4ReadingandWritingDifferentTypesofDataReadingMultipleRecordsperObservationPartialSASLogNOTE:9recordswerereadfromtheinfile'addresses.dat'.Theminimumrecordlengthwas8.Themaximumrecordlengthwas20.NOTE:ThedatasetWORK.ADDRESShas3observationsand5variables.86ReadingMultipleRecordsperObservationprocprintdata=addressnoobs;run;PROCPRINTOutputLNameFNameCityStatePhoneFarrSueAnaheimCA869-7008AndersonKayB.ChicagoIL483-3321TennenbaumMaryAnnJeffersonMO589-9030c04s2d1.sas87 4.2ControllingwhenaRecordLoads4-51MixedRecordTypesNotallrecordshavethesameformat.101USA1-20-19993295.503034EUR30JAN19991876,30101USA1-30-19992938.00128USA2-5-19992908.741345EUR6FEB19993145,60109USA3-17-19992789.10ThedatesarerepresenteddifferentlyandthedecimalplacesandcommasarereversedfortheUSAandEuropeansalesfigures.88DesiredOutputSalesSaleIDLocationDateAmount101USA142643295.503034EUR142741876.30101USA142742938.00128USA142802908.741345EUR142813145.60109USA143202789.1089 4-52Chapter4ReadingandWritingDifferentTypesofDataTheINPUTStatementMultipleINPUTstatementsareneeded.inputSalesID$Location$;ifLocation='USA'theninputSaleDate:mmddyy10.Amount;elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;90MultipleInputStatements:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;run;InputBufferInitializePDVtomissingPDVSalesIDLocationSaleDateAmount..91... 4.2ControllingwhenaRecordLoads4-53MultipleInputStatements:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;run;InputBufferPDVSalesIDLocationSaleDateAmount..92...MultipleInputStatements:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;run;InputBuffer101USA1-20-19993295.50PDVSalesIDLocationSaleDateAmount..93... 4-54Chapter4ReadingandWritingDifferentTypesofDataMultipleInputStatements:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;run;InputBuffer101USA1-20-19993295.50PDVSalesIDLocationSaleDateAmount101USA..94...MultipleInputStatements:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50TrueinputSalesID$Location$;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;run;InputBuffer101USA1-20-19993295.50PDVSalesIDLocationSaleDateAmount101USA..95... 4.2ControllingwhenaRecordLoads4-55MultipleInputStatements:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;run;InputBuffer3034EUR30JAN19991876,30PDVSalesIDLocationSaleDateAmount101USA..96...MultipleInputStatements:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;run;InputBuffer3034EUR30JAN19991876,30PDVSalesIDLocationSaleDateAmount101USA..97... 4-56Chapter4ReadingandWritingDifferentTypesofDataMultipleInputStatements:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;run;InputBuffer3034EUR30JAN19991876,30InvaliddatamessagewrittentologPDVSalesIDLocationSaleDateAmount101USA..98...MultipleInputStatements:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'thenAutomaticreturninputSaleDate:date9.Amount:commax8.;InputBufferrun;Automaticoutput3034EUR30JAN19991876,30PDVSalesIDLocationSaleDateAmount101USA..99... 4.2ControllingwhenaRecordLoads4-57MultipleInputStatements:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.ContinueprocessingAmount:commax8.;run;untilendoftherawdatafileInputBuffer101USA1-30-19992938.00PDVSalesIDLocationSaleDateAmount101USA..100MultipleINPUTStatementsPartialSASLogNOTE:6recordswerereadfromtheinfile'sales.dat'.Theminimumrecordlengthwas24.Themaximumrecordlengthwas26.NOTE:ThedatasetWORK.SALEShas3observationsand4variables.101 4-58Chapter4ReadingandWritingDifferentTypesofDataUndesirableOutputSalesSaleIDLocationDateAmount101USA..101USA..1345EUR..102TheSingleTrailing@Thesingletrailing@holdsarawdatarecordintheinputbufferuntilSAS¢executesanINPUTstatementwithnotrailing@or¢beginsthenextiterationoftheDATAstep.GeneralformofanINPUTstatementwiththesingletrailing@:INPUTINPUTvar1var2var3…@var1var2var3…@;;103 4.2ControllingwhenaRecordLoads4-59ProcessingtheSingleTrailing@HoldrecordfornextINPUTstatementLoadnextrecordinputSalesID$Location$@;iflocation='USA'theninputSaleDate:mmddyy10.Amount;elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;105...SingleTrailing@:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$@;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;run;InputBufferSalesIDLocationSaleDateAmount..106... 4-60Chapter4ReadingandWritingDifferentTypesofDataSingleTrailing@:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$@;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;run;InputBuffer101USA1-20-19993295.50SalesIDLocationSaleDateAmount..107...SingleTrailing@:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$@;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;run;InputBuffer101USA1-20-19993295.50SalesIDLocationSaleDateAmount101USA..108... 4.2ControllingwhenaRecordLoads4-61SingleTrailing@:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$@;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'thenHoldrecordinputSaleDate:date9.Amount:commax8.;run;InputBuffer101USA1-20-19993295.50SalesIDLocationSaleDateAmount101USA..109...SingleTrailing@:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50TrueinputSalesID$Location$@;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;run;InputBuffer101USA1-20-19993295.50SalesIDLocationSaleDateAmount101USA..110... 4-62Chapter4ReadingandWritingDifferentTypesofDataSingleTrailing@:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$@;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;run;InputBuffer101USA1-20-19993295.50SalesIDLocationSaleDateAmount101USA111...SingleTrailing@:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$@;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;run;InputBuffer101USA1-20-19993295.50SalesIDLocationSaleDateAmount101USA142643295.50112... 4.2ControllingwhenaRecordLoads4-63SingleTrailing@:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$@;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'thenAutomaticreturninputSaleDate:date9.Amount:commax8.;InputBufferrun;Automaticoutput101USA1-20-19993295.50SalesIDLocationSaleDateAmount101USA142643295.50113Writeobservationtosales....SingleTrailing@:Executiondatasales;RawDataFilelengthSalesID$4Location$3;infile'raw-data-file';101USA1-20-19993295.50inputSalesID$Location$@;3034EUR30JAN19991876,30101USA1-30-19992938.00ifLocation='USA'then128USA2-5-19992908.74inputSaleDate:mmddyy10.1345EUR6FEB19993145,60Amount;109USA3-17-19992789.10elseifLocation='EUR'theninputSaleDate:date9.ContinueprocessingAmount:commax8.;run;untilendoftherawdatafileInputBuffer101USA1-20-19993295.50SalesIDLocationSaleDateAmount..114 4-64Chapter4ReadingandWritingDifferentTypesofDataMixedRecordTypesPartialSASLogNOTE:6recordswerereadfromtheinfile'sales.dat'.Theminimumrecordlengthwas24.Themaximumrecordlengthwas26.NOTE:ThedatasetWORK.SALEShas6observationsand4variables.115MixedRecordTypesprocprintdata=salesnoobs;run;PROCPRINTOutputSalesSaleIDLocationDateAmount101USA142643295.503034EUR142741876.30101USA142742938.00128USA142802908.741345EUR142813145.60109USA143202789.10c04s2d2.sas116 4.2ControllingwhenaRecordLoads4-65SubsettingfromaRawDataFileThisscenariousestherawdatafilefromthepreviousexample.101USA1-20-19993295.503034EUR30JAN19991876,30101USA1-30-19992938.00128USA2-5-19992908.741345EUR6FEB19993145,60109USA3-17-19992789.10ThedatesarerepresenteddifferentlyandthedecimalplacesandcommasarereversedfortheUSAandEuropeansalesfigures.117DesiredOutputThesalesmanagerwantstoseesalesfortheEuropeanbranchonly.SalesSaleIDLocationDateAmount3034EUR142741876.301345EUR142813145.60118 4-66Chapter4ReadingandWritingDifferentTypesofDataTheSubsettingIFStatementdataeurope;lengthSalesID$4Location$3;infile'raw-data-file';inputSalesID$Location$@;ifLocation='USA'theninputSaleDate:mmddyy10.Amount;elseifLocation='EUR'theninputSaleDate:date9.Amount:commax8.;ifLocation='EUR';run;119TheSubsettingIFStatementThesubsettingIFshouldappearasearlyintheprogramaspossiblebutafterthevariableshavebeenassignedvalues.120 4.2ControllingwhenaRecordLoads4-67TheSubsettingIFStatementdataeurope;lengthSalesID$4Location$3;infile'raw-data-file';inputSalesID$Location$@;ifLocation='EUR';inputSaleDate:date9.Amount:commax8.;run;BecausetheprogramreadsonlyEuropeansales,theINPUTstatementforUSAsalesisnotneeded.121SubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74inputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.Amount:commax8.;run;InputBufferInitializePDVtomissingSalesIDLocationSaleDateAmount..122... 4-68Chapter4ReadingandWritingDifferentTypesofDataSubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74inputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.Amount:commax8.;run;InputBufferSalesIDLocationSaleDateAmount..123...SubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74inputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.Amount:commax8.;run;InputBuffer101USA1-20-19993295.50SalesIDLocationSaleDateAmount..124... 4.2ControllingwhenaRecordLoads4-69SubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74inputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.Amount:commax8.;run;InputBuffer101USA1-20-19993295.50SalesIDLocationSaleDateAmount101USA..125...SubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74inputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.Amount:commax8.;Holdrecordrun;InputBuffer101USA1-20-19993295.50SalesIDLocationSaleDateAmount101USA..126... 4-70Chapter4ReadingandWritingDifferentTypesofDataSubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74FalseinputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.Amount:commax8.;run;InputBuffer101USA1-20-19993295.50SalesIDLocationSaleDateAmount101USA..127...SubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74inputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.AutomaticreturnAmount:commax8.;run;NoautomaticInputBufferoutput101USA1-20-19993295.50SalesIDLocationSaleDateAmount101USA..128... 4.2ControllingwhenaRecordLoads4-71SubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74inputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.Amount:commax8.;run;InputBuffer101USA1-20-19993295.50ReinitializePDVSalesIDLocationSaleDateAmount..129...SubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74inputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.Amount:commax8.;run;InputBuffer101USA1-20-19993295.50SalesIDLocationSaleDateAmount..130... 4-72Chapter4ReadingandWritingDifferentTypesofDataSubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74inputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.Amount:commax8.;run;InputBuffer3034EUR30JAN19991876,30SalesIDLocationSaleDateAmount..131...SubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74inputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.Amount:commax8.;run;InputBuffer3034EUR30JAN19991876,30SalesIDLocationSaleDateAmount3034EUR..132... 4.2ControllingwhenaRecordLoads4-73SubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74inputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.HoldrecordAmount:commax8.;run;InputBuffer3034EUR30JAN19991876,30SalesIDLocationSaleDateAmount3034EUR..133...SubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74TrueinputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.Amount:commax8.;run;InputBuffer3034EUR30JAN19991876,30SalesIDLocationSaleDateAmount3034EUR..134... 4-74Chapter4ReadingandWritingDifferentTypesofDataSubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74inputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.Amount:commax8.;run;InputBuffer3034EUR30JAN19991876,30SalesIDLocationSaleDateAmount3034EUR142741876.30135...SubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74inputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.Amount:commax8.;run;AutomaticAutomaticreturnoutputInputBuffer3034EUR30JAN19991876,30SalesIDLocationSaleDateAmount3034EUR142741876.30136Writeobservationtoeurope.... 4.2ControllingwhenaRecordLoads4-75SubsettingObservations:ExecutionRawDataFiledataeurope;lengthSalesID$4101USA1-20-19993295.503034EUR30JAN19991876,30Location$3;101USA1-30-19992938.00infile'raw-data-file';128USA2-5-19992908.74inputSalesID$Location$@;1345EUR6FEB19993145,60ifLocation='EUR';109USA3-17-19992789.10inputSaleDate:date9.Amount:commax8.;run;ContinueprocessinguntilendoftherawdatafileInputBuffer3034EUR30JAN19991876,30SalesIDLocationSaleDateAmount..137c04s2d3.sasTheSubsettingIFStatementprocprintdata=europenoobs;run;SalesSaleIDLocationDateAmount3034EUR142741876.301345EUR142813145.60138c04s2d3.sas 4-76Chapter4ReadingandWritingDifferentTypesofDataMultipleObservationsperRecordArawdatafilecontainseachemployee’sidentificationnumberandthisyear’scontributiontohisorherretirementplan.Eachrecordcontainsinformationformultipleemployees.E009731400E098722003E731502400E456714500E348051980139DesiredOutputTheoutputSASdatasetshouldhaveoneobservationperemployee.EmpIDContribE009731400E098722003E731502400E456714500E348051980140 4.2ControllingwhenaRecordLoads4-77Processing:WhatIsRequired?E009731400E098722003E731502400ReadforReadforReadforObs.1Obs.2Obs.3ProcessProcessProcessOtherOtherOtherStatementsStatementsStatementsOutputOutputOutput143TheDoubleTrailing@Thedoubletrailing@holdstherawdatarecordacrossiterationsoftheDATAstepuntilthelinepointermovespasttheendoftheline.INPUTINPUTvar1var2var3…@@var1var2var3…@@;;144!Thedoubletrailing@shouldonlybeusedwithlistinput.Ifusedwithcolumnorformattedinput,aninfiniteloopcanresult. 4-78Chapter4ReadingandWritingDifferentTypesofDataTheDoubleTrailing@datawork.retire;lengthEmpID$6;infile'raw-data-file';inputEmpID$Contrib@@;run;Holduntilendofrecord145CreatingMultipleObservationsperRecordPartialSASLogNOTE:2recordswerereadfromtheinfile'retire.dat'.Theminimumrecordlengthwas35.Themaximumrecordlengthwas36.NOTE:SASwenttoanewlinewhenINPUTstatementreachedpasttheendofaline.NOTE:ThedatasetWORK.RETIREhas5observationsand2variables.The"SASwenttoanewline"messageisexpectedbecausethedoubletrailing@indicatesthatSASshouldreaduntiltheendofeachrecord.146 4.2ControllingwhenaRecordLoads4-79CreatingMultipleObservationsperRecordprocprintdata=retirenoobs;run;PROCPRINTOutputEmpIDContribE009731400E098722003E731502400E456714500E348051980c04s2d4.sas147Trailing@versusDoubleTrailing@OptionEffectTrailing@Holdsrawdatarecorduntil1)anINPUTstatementwithINPUTvar-1...@;notrailing@2)thenextiterationoftheDATAstep.Doubletrailing@HoldsrawdatarecordsintheinputbufferuntilSASreadspasttheendoftheline.INPUTvar-1...@@;148Thesingletrailing@andthedoubletrailing@aremutuallyexclusive;theycannotandshouldnotbeusedtogether.IftheybothappearinthesameINPUTstatement,thelastonespecifiedisused.TheMISSOVERoptionisalsoinvalidwiththedoubletrailing@. 4-80Chapter4ReadingandWritingDifferentTypesofDataExercises4.ReadingMultipleRecordsperObservationMedicaldataisstoredintherawdatafileBLOODTYP.Thefirstrecordcontainsthepatient’sidentificationnumberandthepatient’sfirstandlastnames.Thesecondrecordcontainsacodespecifyingthemedicalplan,thepatient’sbloodtype,acodeindicatingwhetherthepatienthasanyallergies,andthenumberofdependantscoveredbythefamily’shealthplan.FirstRecordOrderFieldNotes1IDNumber5-charactercode2LastNameLongestvalueis9characters.3FirstNameLongestvalueis11characters.SecondRecordOrderFieldNotes1PlanType1-charactercode2BloodTypeLongestvalueis3characters.3AllergyCode1-charactercode:Y=Yes,N=No4NumberofDependantsNumericfieldSampleRecordsE1009MORGANGEORGEFO+Y1E1017WELCHDARIUSFAB+N2E1036MOORELESLIESAB+Y1E1037EDWARDSJENNIFERFB-Y1E1038WASHBURNGAYLENB+Y1 4.2ControllingwhenaRecordLoads4-81CreateaSASdatasetnamedwork.medicalthatcontainsthepatient’sidentificationnumber,firstname,lastname,andbloodtype.PartialListingofwork.medicalObsIDLNameFNameBlood1E1009MORGANGEORGEO+2E1017WELCHDARIUSAB+3E1036MOORELESLIEAB+4E1037EDWARDSJENNIFERB-5E1038WASHBURNGAYLEB+6E1050TUTTLETHOMASA+7E1065CHAPMANNEILO+!Youdonothavetoreadallofthefields.5.ReadingMixedRecordTypesMedicaldataisstoredintherawdatafileALLERGY.Thefirstsixfieldsarealwaysasfollows:FirstPartofRecordOrderFieldNotes1IDNumber5-charactercode2LastNameLongestvalueis9characters3FirstNameLongestvalueis11characters4PlanType1-charactercode5BloodTypeLongestvalueis3characters6AllergyCode1-charactercode:Y=Yes,N=NoIfthepatienthasanallergy(AllergyCode=Y),thentherestoftherecordisasfollows:7AllergyType2-charactercodeindicatingtypeofallergy8NumberofDependantsNumericfieldIfthepatientdoesnothaveanallergy(AllergyCode=N),thentherestoftherecordisasfollows:7NumberofDependantsNumericfield 4-82Chapter4ReadingandWritingDifferentTypesofDataSampleRecordsE1009MORGANGEORGEFO+YDY1E1017WELCHDARIUSFAB+N2E1036MOORELESLIESAB+YSM1E1037EDWARDSJENNIFERFB-YHF1E1038WASHBURNGAYLENB+YPA1E1050TUTTLETHOMASSA+N2E1065CHAPMANNEILFO+N2CreateaSASdatasetnamedwork.allergies.PartialListingofwork.allergiesAlgyObsIDLNameFNamePlanBloodAllergyTypeDependants1E1009MORGANGEORGEFO+YDY12E1017WELCHDARIUSFAB+N23E1036MOORELESLIESAB+YSM14E1037EDWARDSJENNIFERFB-YHF15E1038WASHBURNGAYLENB+YPA16E1050TUTTLETHOMASSA+N27E1065CHAPMANNEILFO+N28E1076VENTERRANDALLNA+N19E1094STARRALTONNB+YSF16.SubsettingfromaRawDataFile(Optional)ModifytheDATAstepyouwroteinthepreviousproblemtocreateaSASdatasetnamedwork.allergies2thatcontainsonlypatientswithallergies.Youshouldget11observations.PartialListingofwork.allergies2AlgyObsIDLNameFNamePlanBloodAllergyTypeDependants1E1009MORGANGEORGEFO+YDY12E1036MOORELESLIESAB+YSM13E1037EDWARDSJENNIFERFB-YHF14E1038WASHBURNGAYLENB+YPA1 4.2ControllingwhenaRecordLoads4-837.ReadingRawDatawithMultipleObservationsperRecordTherawdatafileTRANSACTcontainsdailybanktransactionsforagivenaccount.Foreachtransaction,thefollowinginformationisstored:OrderFieldNotes1DateofTransactionWritteninDATE9.2TypeofTransactionC=deposit(credit),D=withdrawal(debit)3AmountofTransactionWritteninCOMMA9.SampleRecords03JAN2001C9,25304JAN2001D12,13506JAN2001C10,56210JAN2001D35,95015JAN2001C95121JAN2001C1,22625JAN2001C8628JAN2001C27,50031JAN2001D75,900CreateaSASdatasetnamedwork.transactionsthatcontainsalltransactions.Listingofwork.transactionsObsDateTypeAmount114978C9253214979D12135314981C10562414985D35950514990C951614996C1226715000C86815003C27500915006D75900 4-84Chapter4ReadingandWritingDifferentTypesofData8.CreatingMultipleSASDataSetsfromaSingleRawDataFile(Optional)ModifytheDATAstepyouwroteinExercise7tocreatetwoSASdatasets.Namethefirstdatasetwork.credits;itshouldcontainallthedepositinformation.Nametheseconddatasetwork.debits;itshouldcontainallthewithdrawalinformation.Hint:CreatebothdatasetsinoneDATAstepbylistingthembothintheDATAstatementandusingconditionallogicwithanOUTPUTstatement(showninSection2.2,“WritingtoMultipleDataSets”).Listingofwork.creditsObsDateTypeAmount114978C9253214981C10562314990C951414996C1226515000C86615003C27500Listingofwork.debitsObsDateTypeAmount114979D12135214985D35950315006D759009.SubsettingfromaFixed-ColumnRawDataFile(Optional)TheREADEMPSprogramreadsafixed-columnrawdatafileandoutputsonlythesalesclerks.datasalclrks;infile'raw-data-file';input@1Division$20.@21HireDatemmddyy10.@31Salarydollar10.2@41LastName$15.@56FirstName$15.@71Country$15.@86Location$10.@96IdNumber$6.@112JobCode$6.;ifjobcode='SALCLK';run;procprintdata=salclrksnoobs;title'EmployeeInformationforSalesclerks';run; 4.2ControllingwhenaRecordLoads4-85a.IncludetheREADEMPSprograminyourProgramEditor.Submittheprogramandverifytheoutput.PartialOutputEmployeeInformationforSalesclerksHireDivisionDateSalaryLastNameFirstNameSALES810729000DANZINMATHIASSALES1249225000HALLDREMAA.SALES920541000BOOZERKRAIGE.SALES829027000LIEBLEIIIJANSALES1265817000TOUGERARTHURSALES783838000COLEJONIL.SALES1006431000FINNBETTYL.SALES862044000KATZPATRICIAB.SALES909738000POTTSPAULSALES1249244000BENTZMARIEIdJobCountryLocationNumberCodeBELGIUMBRUSSELSE0019SALCLKUSACARYE0044SALCLKUSACARYE0058SALCLKUSAORLANDOE0093SALCLKUSACARYE0104SALCLKUSACARYE0113SALCLKUSABEDMINSTERE0149SALCLKUSAKANSASCITE0171SALCLKUSACARYE0199SALCLKFRANCEPARISE0229SALCLKb.Modifytheprogramsothatitproducestheoutputdatasetasefficientlyaspossible.!Fixedcolumnfieldscanbereadinanyorder. 4-86Chapter4ReadingandWritingDifferentTypesofData10.UsingtheAbsoluteLinePointerControl(Optional)TherawdatafileEMPTWOhasemployeeinformationthatspanstworecordsasshownbelow.Record1OrderFieldNotes1DivisionLongestvalueis20characters2HireDateWritteninMMDDYY10.3SalaryStandardnumericfieldRecord2OrderFieldNotes1IDNumber6charactercode2LastNameLongestvalueis15characters.3FirstNameLongestvalueis15characters.SampleRecordsFLIGHTOPTS,03/11/1992,25000E0001,MILLS,DOROTHYEFINANCE,12/19/1983,27000E0002,BOWER,EILEENA.HR&FACIL,03/12/1985,120000E0003,READING,TONYR.HR&FACIL,10/16/1989,42000ReadtheEMPTWOrawdatafiletocreatetheSASdatasetwork.empinfo.Usetheabsolutelinepointertocontrolthedefaultorderofthefields,sothatthevariablesintheSASdatasetareinthefollowingorder:1)IdentificationNumber2)LastName3)FirstName4)Division5)HireDate6)Salary 4.2ControllingwhenaRecordLoads4-87Listingofwork.empinfoIdHireObsNumberLastNameFirstNameDivisionDateSalary1E0001MILLSDOROTHYEFLIGHTOPTS11758250002E0002BOWEREILEENA.FINANCE8753270003E0003READINGTONYR.HR&FACIL92021200004E0004JUDDCAROLA.HR&FACIL10881420005E0005WONSIDHANNAAIRPORTOPTS8023190006E0006ANDERSONCHRISTOPHERSALES11439310007E0007MASSENGILLANNETTEM.FLIGHTOPTS8440290008E0008BADINEDAVIDCORPORATE11733850009E0009DEMENTCHARLESFINANCE98873400010E0010FOSKEYJERED.AIRPORTOPTS1128429000!Formoreinformationontheabsolutelinepointercontrol,seethenoteontherelativelinepointercontrol.Forhelponcontrollingvariablelengthwhilepreservingtheirorder,seethenotesonusinginformatsontheINPUTstatementinChapter4,Section1. 4-88Chapter4ReadingandWritingDifferentTypesofData4.3ReadingHierarchicalRawDataFilesObjectives¢Readahierarchicalfileandcreateoneobservationperdetailrecord.¢Readahierarchicalfileandcreateoneobservationperheaderrecord.151ProcessingHierarchicalFilesManyfilesarehierarchicalinstructure,consistingof¢aheaderrecord¢zeroormorerelateddetailrecords.HeaderTypically,eachrecordcontainsafieldDetailthatidentifieswhetheritisaheaderDetailrecordoradetailrecord.HeaderHeaderDetailHeaderDetailDetail152 4.3ReadingHierarchicalRawDataFiles4-89ProcessingHierarchicalFilesYoucanreadahierarchicalfileintoaSASdatasetbycreatingoneobservationperdetailrecordandstoringtheheaderinformationaspartofeachobservation.HierarchicalFileSASDataSetHeader1HeaderDetailDetail1VariablesVariablesDetail2Detail3Header1Detail1Header2Header1Detail2Detail1Header1Detail3Header3Header2Detail1Detail1Header3Detail1Detail2Header3Detail2153ProcessingHierarchicalFilesYoucanalsocreateoneobservationperheaderrecordandstoretheinformationfromdetailrecordsinsummaryvariables.HierarchicalFileSASDataSetHeader1HeaderSummaryDetail1VariablesVariablesDetail2Detail3Header1Summary1Header2Header2Summary2Detail1Header3Summary3Header3Detail1Detail2154 4-90Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObservationperDetailRecordTherawdatafilehasaE:Adams:SusanheaderrecordcontainingD:Michael:CthenameoftheemployeeD:Lindsay:CandadetailrecordforE:Porter:DavideachdependantonD:Susan:Stheemployee’shealthE:Lewis:DorianD.insurance.D:Richard:CE:Dansky:IanE:Nicholls:JamesD:Roberta:CE:Slaydon:MarlaD:John:S155DesiredOutputHumanResourceswantsalistofallthedependantsandthenameoftheassociatedemployee.EmpLNameEmpFNameDepNameRelationAdamsSusanMichaelCAdamsSusanLindsayCPorterDavidSusanSLewisDorianD.RichardCNichollsJamesRobertaCSlaydonMarlaJohnS156 4.3ReadingHierarchicalRawDataFiles4-91AHierarchicalFile¢NotalltherecordsE:Adams:Susancontainthesamefields.D:Michael:CD:Lindsay:C¢ThefieldsareseparatedE:Porter:Davidbycolons.D:Susan:S¢ThereisafieldindicatingE:Lewis:DorianD.whethertherecordisaD:Richard:Cheaderoradetailrecord.E:Dansky:IanE:Nicholls:JamesD:Roberta:CE:Slaydon:MarlaD:John:S157HowtoReadtheRawDatainputType$@;ifType='E'theninputEmpLName$EmpFName$;elseinputDepName$Relation$;158 4-92Chapter4ReadingandWritingDifferentTypesofDataHowtoOutputOnlytheDependantsinputType$@;ifType='E'theninputEmpLName$EmpFName$;elsedo;inputDepName$Relation$;output;end;159CreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:Send;InputBufferrun;DTypeEmpLNameEmpFNameDepNameRelation160... 4.3ReadingHierarchicalRawDataFiles4-93CreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:Send;InputBufferrun;E:Adams:SusanDTypeEmpLNameEmpFNameDepNameRelation161...CreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:Send;InputBufferrun;E:Adams:SusanDTypeEmpLNameEmpFNameDepNameRelationE162... 4-94Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:SHoldrecordend;InputBufferrun;E:Adams:SusanDTypeEmpLNameEmpFNameDepNameRelationE163...CreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:DavidTrueinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:Send;InputBufferrun;E:Adams:SusanDTypeEmpLNameEmpFNameDepNameRelationE164... 4.3ReadingHierarchicalRawDataFiles4-95CreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:Send;InputBufferrun;E:Adams:SusanDTypeEmpLNameEmpFNameDepNameRelationEAdamsSusan165...CreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:Send;NooutputInputBufferrun;AutomaticE:Adams:SusanreturnDTypeEmpLNameEmpFNameDepNameRelationEAdamsSusan166... 4-96Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:Send;InputBufferrun;E:Adams:SusanReinitializePDVDTypeEmpLNameEmpFNameDepNameRelation167...CreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:Send;InputBufferrun;E:Adams:SusanDTypeEmpLNameEmpFNameDepNameRelation168... 4.3ReadingHierarchicalRawDataFiles4-97CreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:Send;InputBufferrun;D:Michael:CDTypeEmpLNameEmpFNameDepNameRelation169...CreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:Send;InputBufferrun;D:Michael:CDTypeEmpLNameEmpFNameDepNameRelationD170... 4-98Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:SHoldrecordend;InputBufferrun;D:Michael:CDTypeEmpLNameEmpFNameDepNameRelationD171...CreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SFalseinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:Send;InputBufferrun;D:Michael:CDTypeEmpLNameEmpFNameDepNameRelationD172... 4.3ReadingHierarchicalRawDataFiles4-99CreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:Send;InputBufferrun;D:Michael:CDTypeEmpLNameEmpFNameDepNameRelationD173...CreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:Send;InputBufferrun;D:Michael:CDTypeEmpLNameEmpFNameDepNameRelationDMichaelC174... 4-100Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperDetailRecord:Executiondatadependants(drop=Type);E:Adams:SusanlengthType$1EmpLNameEmpFNameD:Michael:CDepName$20Relation$1;D:Lindsay:CE:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.ifType='E'thenD:Richard:CinputEmpLName$EmpFName$;E:Dansky:IanE:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:Marlaoutput;D:John:Send;InputBufferrun;ExplicitAutomaticreturnoutputD:Michael:CDTypeEmpLNameEmpFNameDepNameRelationDMichaelC175UndesirableOutputEmpEmpLNameFNameDepNameRelationMichaelCLindsayCSusanSRichardCRobertaCJohnS176 4.3ReadingHierarchicalRawDataFiles4-101TheRETAINStatement(Review)GeneralformoftheRETAINstatement:RETAINRETAINvariable-namevariable-name<>;;TheRETAINstatementpreventsSASfromreinitializingthevaluesofnewvariablesatthetopoftheDATAstep.Thismeansthatvaluesfrompreviousrecordsareavailableforprocessing.177Bydefault,variablesreferencedintheRETAINstatementaresettomissingbeforethefirstiterationoftheDATAstep.Tochangethis,youcanspecifyaninitialvalueafterthevariable’sname.Formore®information,seeChapter3,“SummarizingData,”orSASLanguageReference:Dictionary.VariablesreferencedwiththeRETAINstatementareintheoutputdatasetonlyiftheyarereferencedelsewhereintheDATAsteporassignedinitialvalues.HoldEmpLNameandEmpFNamedatadependants(drop=Type);lengthType$1EmpLNameEmpFNameDepName$20Relation$1;retainEmpLNameEmpFName;infile'raw-data-file'dlm=':';inputType$@;ifType='E'theninputEmpLName$EmpFName$;elsedo;inputDepName$Relation$;output;end;run;178 4-102Chapter4ReadingandWritingDifferentTypesofDataRetainingValues:Compilationdatadependants(drop=Type);lengthType$1EmpLNameEmpFNameDepName$20Relation$1;retainEmpLNameEmpFName;infile'raw-data-file'dlm=':';inputType$@;ifType='E'theninputEmpLName$EmpFName$;elsedo;inputDepName$Relation$;output;end;run;InputBufferDRRTypeEmpLNameEmpFNameDepNameRelation179...RetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;InitializePDVtomissingDRRTypeEmpLNameEmpFNameDepNameRelation180... 4.3ReadingHierarchicalRawDataFiles4-103RetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;DRRTypeEmpLNameEmpFNameDepNameRelation181...RetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;E:Adams:SusanDRRTypeEmpLNameEmpFNameDepNameRelation182... 4-104Chapter4ReadingandWritingDifferentTypesofDataRetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;E:Adams:SusanDRRTypeEmpLNameEmpFNameDepNameRelationE183...RetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:SHoldrecordoutput;end;InputBufferrun;E:Adams:SusanDRRTypeEmpLNameEmpFNameDepNameRelationE184... 4.3ReadingHierarchicalRawDataFiles4-105RetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:STrueinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;E:Adams:SusanDRRTypeEmpLNameEmpFNameDepNameRelationE185...RetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;E:Adams:SusanDRRTypeEmpLNameEmpFNameDepNameRelationEAdamsSusan186... 4-106Chapter4ReadingandWritingDifferentTypesofDataRetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;NooutputAutomaticE:Adams:SusanreturnDRRTypeEmpLNameEmpFNameDepNameRelationEAdamsSusan187...RetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;E:Adams:SusanReinitializePDVDRRTypeEmpLNameEmpFNameDepNameRelationAdamsSusan188... 4.3ReadingHierarchicalRawDataFiles4-107RetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;E:Adams:SusanDRRTypeEmpLNameEmpFNameDepNameRelationAdamsSusan189...RetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;D:Michael:CDRRTypeEmpLNameEmpFNameDepNameRelationAdamsSusan190... 4-108Chapter4ReadingandWritingDifferentTypesofDataRetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;D:Michael:CDRRTypeEmpLNameEmpFNameDepNameRelationDAdamsSusan191...RetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:SHoldrecordoutput;end;InputBufferrun;D:Michael:CDRRTypeEmpLNameEmpFNameDepNameRelationDAdamsSusan192... 4.3ReadingHierarchicalRawDataFiles4-109RetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SFalseinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;D:Michael:CDRRTypeEmpLNameEmpFNameDepNameRelationDAdamsSusan193...RetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;D:Michael:CDRRTypeEmpLNameEmpFNameDepNameRelationDAdamsSusan194... 4-110Chapter4ReadingandWritingDifferentTypesofDataRetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;D:Michael:CDTypeEmpLNameEmpFNameDepNameRelationDAdamsSusanMichaelC195...RetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;ExplicitAutomaticoutputD:Michael:CreturnDRRTypeEmpLNameEmpFNameDepNameRelationDAdamsSusanMichaelC196... 4.3ReadingHierarchicalRawDataFiles4-111RetainingValues:Executiondatadependants(drop=Type);lengthType$1EmpLNameEmpFNameE:Adams:SusanD:Michael:CDepName$20Relation$1;D:Lindsay:CretainEmpLNameEmpFName;E:Porter:Davidinfile'raw-data-file'dlm=':';D:Susan:SinputType$@;E:Lewis:DorianD.D:Richard:CifType='E'thenE:Dansky:IaninputEmpLName$EmpFName$;E:Nicholls:Jameselsedo;D:Roberta:CinputDepName$Relation$;E:Slaydon:MarlaD:John:Soutput;end;InputBufferrun;ContinueprocessingD:Michael:CuntilendoftherawdatafileDRRTypeEmpLNameEmpFNameDepNameRelationDAdamsSusanMichaelC197CreatingOneObservationperDetailRecordprocprintdata=work.dependantsnoobs;run;PROCPRINTOutputEmpLNameEmpFNameDepNameRelationAdamsSusanMichaelCAdamsSusanLindsayCPorterDavidSusanSLewisDorianD.RichardCNichollsJamesRobertaCSlaydonMarlaJohnSWhydoesIanDanskynotappearintheoutput?c04s3d1.sas198 4-112Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObservationperHeaderRecordE:E01442¢EmployeeinsuranceisD:Michael:Cfreefortheemployees.D:Lindsay:C¢Eachemployeepays$50E:E00705permonthforaspouse’sD:Susan:Sinsurance.E:E01577¢Eachemployeepays$25D:Richard:Cpermonthforachild’sE:E00997insurance.E:E00955D:Roberta:CE:E00224D:John:S199DesiredOutputHumanResourceswantsalistofallemployeesandtheirmonthlypayrolldeductionsforinsurance.IDDeductE0144250E0070550E0157725E009970E0095525E0022450200 4.3ReadingHierarchicalRawDataFiles4-113CalculatingtheValueofDeductE:E01442ThevaluesofDeductD:Michael:CchangeaccordingtotheD:Lindsay:C¢typeofrecordreadE:E00705D:Susan:S¢valueofRelationE:E01577whenType='D'.D:Richard:CE:E00997E:E00955D:Roberta:CE:E00224D:John:S201RetainingIDValuesofIDandDeductmustbeheldacrossiterationsoftheDATAstep.retainID;¢IDmustberetainedwithaRETAINstatement.¢Deductiscreatedwithasumstatement,soitisautomaticallyretained.202 4-114Chapter4ReadingandWritingDifferentTypesofDataWhentoOutput?E:E01442D:Michael:CD:Lindsay:CE:E00705EndObservation1D:Susan:SE:E01577EndObservation2D:Richard:CE:E00997EndObservation3E:E00955EndObservation4D:Roberta:CE:E00224EndObservation5D:John:SEndObservation6203WhenSASLoadsaTypeERecord1.OutputwhatiscurrentlyinthePDV(unlessthisisthefirsttimethroughtheDATAstep).2.Readthenextemployee’sidentificationnumber.3.ResetDeductto0.ifType='E'thendo;if_N_>1thenoutput;inputID$;Deduct=0;end;204 4.3ReadingHierarchicalRawDataFiles4-115WhenSASLoadsaTypeDRecord1.Readthedependant’snameandrelationship.2.Checktherelationship.3.IncrementDeductappropriately.elsedo;inputDepName$Relation$;ifRelation='C'thenDeduct+25;elseDeduct+50;end;WhyisDepNameread?205RetainingIDdatawork.insurance(keep=IDDeduct);lengthType$1ID$6DepName$20Relation$1;retainID;infile'raw-data-file'dlm=':';inputType$@;ifType='E'thendo;if_N_>1thenoutput;inputID$;Deduct=0;end;elsedo;inputDepName$Relation$;ifRelation='C'thenDeduct+25;elseDeduct+50;end;run;206 4-116Chapter4ReadingandWritingDifferentTypesofDataWhatAbouttheLastRecord?E:E01442D:Michael:CD:Lindsay:CE:E00705D:Susan:SE:E01577D:Richard:CE:E00997E:E00955D:Roberta:CE:E00224D:John:SNoautomaticoutput207TheEND=OptionGeneralformoftheEND=option:INFILEINFILE'file-name'file-name'END='END=variable-namevariable-name;;wherevariable-nameisanyvalidSASvariablename.TheEND=optioncreatesavariablethathasthevalue¢1ifitisthelastrecordoftheinputfile¢0otherwise.VariablescreatedwithEND=areautomaticallydropped.208 4.3ReadingHierarchicalRawDataFiles4-117TheEND=Optiondatawork.insurance(keep=IDDeduct);lengthType$1ID$6DepName$20Relation$1;retainID;infile'raw-data-file'dlm=':'end=LastRec;inputType$@;ifType='E'thendo;if_N_>1thenoutput;inputID$;Deduct=0;end;elsedo;inputDepName$Relation$;ifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;run;209CreatingOneObsperHeader:Compilationdatawork.insurance(keep=IDDeduct);lengthType$1ID$6DepName$20Relation$1;retainID;infile'raw-data-file'dlm=':'end=LastRec;inputType$@;ifType='E'thendo;if_N_>1thenoutput;inputID$;Deduct=0;end;elsedo;inputDepName$Relation$;ifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;run;DRDDRDDTypeIDDepNameRelationDeduct_N_LastRec00210... 4-118Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;InitializePDVDRDDRDDTypeIDDepNameRelationDeduct_N_LastRec010211...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;DRDDRDDTypeIDDepNameRelationDeduct_N_LastRec010212... 4.3ReadingHierarchicalRawDataFiles4-119CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;E:E01442DRDDRDDTypeIDDepNameRelationDeduct_N_LastRec010213...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;E:E01442DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE010214... 4-120Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;Holdrecordend;ifLastRecthenoutput;InputBufferrun;E:E01442DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE010215...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:STrueinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;E:E01442DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE010216... 4.3ReadingHierarchicalRawDataFiles4-121CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;FalseE:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;E:E01442DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE010217...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;E:E01442DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecEE01442010218... 4-122Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;Deduct=0E:E01442DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecEE01442010219...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;E:E01442DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecEE01442010220... 4.3ReadingHierarchicalRawDataFiles4-123CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;Falseend;ifLastRecthenoutput;InputBufferrun;E:E01442DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecEE01442010221...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;NooutputInputBufferrun;AutomaticreturnE:E01442DRDDRDDTypeIDDepNameRelationDeduct_N_LASTRECEE01442010222... 4-124Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;ReinitializePDVE:E01442DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE01442020223...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;E:E01442DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE01442020224... 4.3ReadingHierarchicalRawDataFiles4-125CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:Michael:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE01442020225...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:Michael:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE01442020226... 4-126Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;Holdrecordend;ifLastRecthenoutput;InputBufferrun;D:Michael:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE01442020227...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CFalseinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:Michael:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE01442020228... 4.3ReadingHierarchicalRawDataFiles4-127CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:Michael:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE01442MichaelC020229...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;TrueE:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:Michael:C0+25DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE01442MichaelC2520230... 4-128Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;Falseend;ifLastRecthenoutput;InputBufferrun;D:Michael:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE01442MichaelC2520231...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;NooutputInputBufferrun;AutomaticreturnD:Michael:CDRDDRDDTypeIDDepNameRelationDeduct_N_LASTRECDE01442MichaelC2520232... 4.3ReadingHierarchicalRawDataFiles4-129CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;ReinitializePDVD:Michael:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE014422530233...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:Michael:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE014422530234... 4-130Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:Lindsay:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE014422530235...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:Lindsay:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE014422530236... 4.3ReadingHierarchicalRawDataFiles4-131CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;Holdrecordend;ifLastRecthenoutput;InputBufferrun;D:Lindsay:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE014422530237...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CFalseinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:Lindsay:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE014422530238... 4-132Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:Lindsay:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE01442LindsayC020239...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;TrueE:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;25+25D:Lindsay:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE01442LindsayC5030240... 4.3ReadingHierarchicalRawDataFiles4-133CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;Falseend;ifLastRecthenoutput;InputBufferrun;D:Lindsay:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE01442LindsayC5030241...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;NooutputInputBufferrun;AutomaticreturnD:Lindsay:CDRDDRDDTypeIDDepNameRelationDeduct_N_LASTRECDE01442LindsayC5030242... 4-134Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;ReinitializePDVD:Lindsay:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE014425040243...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:Lindsay:CDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE014425040244... 4.3ReadingHierarchicalRawDataFiles4-135CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;E:E00705DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE014425040245...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;E:E00705DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecEE014425040246... 4-136Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;Holdrecordend;ifLastRecthenoutput;InputBufferrun;E:E00705DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecEE014425040247...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:STrueinputType$@;E:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;E:E00705DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecEE014425040248... 4.3ReadingHierarchicalRawDataFiles4-137CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;TrueE:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;E:E00705DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecEE014425040249...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;D:Susan:SinputType$@;TrueE:E01577ifType='E'thendo;if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ExplicitifLastRecthenoutput;InputBufferrun;outputE:E00705DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecEE014425040250 4-138Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperHeader:ExecutionCurrentcontentsofwork.insuranceIDDeductE0144250251...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;E:E00705DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecEE007055040252... 4.3ReadingHierarchicalRawDataFiles4-139CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;Deduct=0E:E00705DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecEE00705040253...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;Falseend;ifLastRecthenoutput;InputBufferrun;E:E00705DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecEE00705040254... 4-140Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;NooutputInputBufferrun;AutomaticreturnE:E00705DRDDRDDTypeIDDepNameRelationDeduct_N_LASTRECEE00705040255...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;ReinitializePDVE:E00705DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE00705050256... 4.3ReadingHierarchicalRawDataFiles4-141CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ContinueprocessingthroughtheifLastRecthenoutput;InputBufferrun;employeerecordforE00224E:E00224DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecEE002240110257...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;E:E00224DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE002240120258... 4-142Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:John:SDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecE002240121259...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:John:SDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE002240121260... 4.3ReadingHierarchicalRawDataFiles4-143CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;Holdrecordend;ifLastRecthenoutput;InputBufferrun;D:John:SDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE002240121261...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CFalseinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:John:SDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE002240121262... 4-144Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:John:SDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE00224JohnS0121263...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;FalseE:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:John:SDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE00224JohnS0121264... 4.3ReadingHierarchicalRawDataFiles4-145CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:John:S0+50DRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE00224JohnS50121265...CreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;TrueelseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;D:John:SDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE00224JohnS50121266... 4-146Chapter4ReadingandWritingDifferentTypesofDataCreatingOneObsperHeader:Executiondatawork.insurance(keep=IDDeduct);E:E01442lengthType$1ID$6DepName$20Relation$1;D:Michael:CretainID;D:Lindsay:Cinfile'raw-data-file'E:E00705dlm=':'end=LastRec;inputType$@;D:Susan:SifType='E'thendo;E:E01577if_N_>1thenoutput;D:Richard:CinputID$;E:E00997Deduct=0;E:E00955end;D:Roberta:Celsedo;E:E00224inputDepName$Relation$;D:John:SifRelation='C'thenDeduct+25;elseDeduct+50;end;ifLastRecthenoutput;InputBufferrun;ExplicitD:John:SoutputDRDDRDDTypeIDDepNameRelationDeduct_N_LastRecDE00224JohnS50121267CreatingOneObservationperHeaderprocprintdata=insurancenoobs;run;PROCPRINTOutputIDDeductE0144250E0070550E0157725E009970E0095525E0022450c04s3d2.sas268 4.3ReadingHierarchicalRawDataFiles4-147SummarizingaHierarchicalFilewithTwoDATASteps(Self-Study)File:c04s3d3.sasItispossibletoreadahierarchicalrawdatafileusingtwoDATAstepsinsteadofthemethodshownabove.Althoughlessefficient,thismethodtendstobeeasiertocode,maintain,anddebug.Step1:ReadthehierarchicalrawdatafileintoaSASdatasetanduseconditionalinput.dataHierStep1;dropDepName;/*WehavetoreadDepName*//*becausethisislistinput,*//*butwedonotneedittosummarize*/lengthType$1ID$6DepName$20Relation$1;retainID;infile'raw-data-file'dlm=':';inputType$@;ifType='E'theninputID$;elseinputDepName$Relation$;run;procprintdata=hierstep1;title'FirstStepinSummarizingaHierarchicalFile';run;FirstStepinSummarizingaHierarchicalFileObsTypeIDRelation1EE014422DE01442C3DE01442C4EE007055DE00705S6EE015777DE01577C8EE009979EE0095510DE00955C11EE0022412DE00224S 4-148Chapter4ReadingandWritingDifferentTypesofDataStep2:TheresultingdatasetisgroupedbyID,thoughtheIDsmightnotbeinorder.YoucanusethetechniquesdescribedinChapter3andtheNOTSORTEDoptionintheBYstatementtosummarizethisdatasetbyID.dataHierstep2;dropTypeRelation;setHierstep1;byIDnotsorted;/*TheNOTSORTEDoptionindicatesthatthe*//*dataisgroupedbytheBYvariablebutthat*//*thevaluesarenotnecessarily*//*insortorder.ThiscreatesFirst.andLast.*/ifFirst.IDthenDeduct=0;ifRelation='C'thenDeduct+25;elseifRelation='S'thenDeduct+50;/*MustmakesureRelation='S'andnotmissing*/ifLast.ID;run;DeductionsforAllEmployeesObsIDDeduct1E01442502E00705503E01577254E0099705E00955256E0022450 4.3ReadingHierarchicalRawDataFiles4-149Exercises11.ReadingaHierarchicalRawDataFileandCreatingOneObservationperDetailRecordTherawdatafileSALARIESishierarchical.Theheaderrecordhastheemployee’sidentificationnumber,firstname,lastname,andthedateheorshewashired.Thedetailrecordshavetheemployee’ssalaryforeachyearthatheorshewasemployedbythecompany.HeaderRecordsOrderFieldNotes1RecordTypeE=Headerrecord,S=Detailrecord2EmployeeIDNumber6-charactercode3FirstNameLongestvalueis8characters4LastNameLongestvalueis8characters5HireDateWritteninDATE9.DetailRecordsOrderFieldNotes1RecordTypeE=Headerrecord,S=Detailrecord2SalaryYear4-digityear3Salary5digitsplusembeddedcomma,e.g.55,555SampleRecordsEE1232JOHNSMITH15OCT1999S199951,684S200056,180S200161,065EE2341ALICEJONES01JUN1997S199765,684S199871,396S199977,604S200084,353S200191,688CreatetheSASdatasetwork.salariesthatcontainsthevariablesID,FName,LName,SalYear,andSalary.Thereshouldbeoneobservationforeachyearthattheemployeeworked. 4-150Chapter4ReadingandWritingDifferentTypesofDataPartialListingofwork.salariesYearlySalariesThrough2001SalObsIDLNameFNameYearSalary1E1232SMITHJOHN1999516842E1232SMITHJOHN2000561803E1232SMITHJOHN2001610654E2341JONESALICE1997656845E2341JONESALICE1998713966E2341JONESALICE1999776047E2341JONESALICE2000843538E2341JONESALICE20019168812.ReadingaHierarchicalRawDataFileandCreatingOneObservationperHeaderRecord(Optional)UsingthesamerawdatafileasinExercise11,createaSASdatasetnamedwork.currentwiththevariablesID,LName,FName,HireDate,andSalary.Thereshouldbeoneobservationforeachemployee,andthevalueofSalaryshouldbeequaltothemostrecentyear’ssalary.Listingofwork.currentSalariesasof2001HireObsIDLNameFNameDateSalary1E1232SMITHJOHN14532610652E2341JONESALICE13666916883E3452MOORELES12352326394E6781LEEJENNIFER11947283055E8321LONGGAYLE13479404406E1052GREENTHOMAS13572394617E1062FOREMANNEIL9991414638E8172THOMPSONRANDY14615406509E1091MCKINSEYSTARR115544095010E9992DALTONRICHARD111414045513.ReadingaHierarchicalFileUsingTwoDATASteps(Optional)UsingthesamerawdatafileasinExercise12,createaSASdatasetnamedwork.twostepandusethetwo-stepprocessdescribedintheself-studysection.Youshouldgetthesameoutputasinthepreviousexercise. 4.3ReadingHierarchicalRawDataFiles4-15114.ReadingaHierarchicalFilewithoutanExplicitIdentifyingField(Optional)TherawdatafileBSTONEScontainsaheaderrecordidentifyingthemonth,plusfiveormoredetailrecordsthatidentifydifferentbirthstonesassociatedwiththatmonth.HeaderRecordFieldNotesMonthLongestvalueis9bytes.Detail1FieldNotesModernBirthstoneLongestvalueis12bytes.Detail2FieldNotesTraditionalBirthstoneLongestvalueis12bytes.Detail3FieldNotesMysticalBirthstoneLongestvalueis11bytes.Detail4FieldNotesAyurvedicBirthstoneLongestvalueis10bytes.Detail5-7FieldNotesOtherBirthstoneLongestvalueis15bytes. 4-152Chapter4ReadingandWritingDifferentTypesofDataSampleRecordsJanuaryGarnetGarnetEmeraldGarnetRoseQuartzFebruaryAmethystAmethystBloodstoneAmethystOnyxMoonstoneMarchAquamarineBloodstoneJadeBloodstoneRockCrystal!Notallrecordshavemorethanone“Other”birthstone.Forexample,Januaryhasonlyonebirthstoneclassifiedas“Other”;Februaryhastwo,andOctoberhasthree.!AyurvedicbirthstonesarethebirthstonesproscribedbytraditionalIndianmedicaltechniques. 4.3ReadingHierarchicalRawDataFiles4-153Usetherawdatafiletocreatework.birthstones,whichhasoneobservationforeachmonth,andonevariableforeachtypeofbirthstone.Listingofwork.birthstonesVariousBirthstonesforEachMonthObsMonthModernTraditionalMysticalAyurvedic1JanuaryGarnetGarnetEmeraldGarnet2FebruaryAmethystAmethystBloodstoneAmethyst3MarchAquamarineBloodstoneJadeBloodstone4AprilDiamondDiamondOpalDiamond5MayEmeraldEmeraldSapphireAgate6JunePearlAlexandriteMoonstonePearl7JulyRubyRubyRubyRuby8AugustPeridotSardonyxDiamondSapphire9SeptemberSapphireSapphireAgateMoonstone10OctoberOpalTourmalineJasperOpal11NovemberYellowTopazCitrinePearlTopaz12DecemberBlueTopazZirconOnyxRubyObsOther1Other2Other31RoseQuartz2OnyxMoonstone3RockCrystal4QuartzWhiteSapphire5ChrysopraseBeryl6OpalMoonstone7Carnelian8Jade9LapisLazuliDiamondChrsolite10PinkTourmalineZirconAquamarine11Diamond12TurquoiseLapisLazuli 4-154Chapter4ReadingandWritingDifferentTypesofData4.4SolutionstoExercises1.ReadingNonstandardData/*z/OS:fileref='.prog2.rawdata(states)';*/procfslistfileref='states.dat';run;datastates;/*z/OS:infile'.prog2.rawdata(states)'dlm='!';*/infile'states.dat'dlm='!';lengthState$14;inputState$Population:comma10.SizeEnterDate:date9.;run;title1'StateNamesandFacts';procprintdata=states;formatEnterDatedate9.;run;2.UsingINFILEStatementOptionstoChangeDefaults/*z/OS:fileref='.prog2.rawdata(aromas)';*/procfslistfileref='aromas.dat';run;dataaromas;lengthConditionCure1Cure2Cure3$11;/*z/OS:infile'.prog2.rawdata(aromas)'dsddlm='';*/infile'aromas.dat'dsddlm=''missover;inputCondition$Cure1$Cure2$Cure3$;run;title1'AromatherapyDataSet';procprintdata=aromas;run; 4.4SolutionstoExercises4-1553.ReadingaFixed-ColumnRawDataFilewithVariableLengthRecords(Optional)Theproblemwiththisrawdatafileisthatnotalltherecordsarethesamelength.Youcanverifythisbylookingatitspropertiesoropeningitinatexteditor.EithertheTRUNCOVERorthePADoptionwouldbeequallyeffectiveinthiscase./*z/OS:fileref='.prog2.rawdata(aromasf)';*/procfslistfileref='aromasf.dat';run;/*ThePADoptionhandlestheproblembyaddingspacestoshorterrecords.*/dataaromasf;/*z/OS:infile'.prog2.rawdata(aromasf)';*/infile'aromasf.dat'pad;input@1Condition$10.@11Cure1$11.@22Cure2$11.@33Cure3$11.;run;title1'ResultsfromPADOption';procprintdata=aromasf;run;/*TheTRUNCOVERoptiontellsSASnottoreadfromthenextlinewhenitrunsoutofdata,buttoassignwhateverithasreadtothevariable.*/dataaromasf;/*z/OS:infile'.prog2.rawdata(aromasf)'truncover;*/infile'aromasf.dat'truncover;input@1Condition$10.@11Cure1$11.@22Cure2$11.@33Cure3$11.;run;title1'ResultsfromTRUNCOVEROption';procprintdata=aromasf;run; 4-156Chapter4ReadingandWritingDifferentTypesofData4.ReadingMultipleRecordsperObservation/*z/OS:fileref='.prog2.rawdata(bloodtyp)';*/procfslistfileref='bloodtyp.dat';run;datamedical(drop=Plan);/*z/OS:infile'.prog2.rawdata(bloodtyp)';*/infile'bloodtyp.dat';lengthID$5LNameFName$11Plan$1Blood$3;inputIDLNameFName/PlanBlood;run;title1'PatientNamesandBloodTypes';procprintdata=medical;run;5.ReadingMixedRecordTypes/*z/OS:fileref='.prog2.rawdata(allergy)';*/procfslistfileref='allergy.dat';run;dataallergies;lengthID$5LNameFName$11Plan$1Blood$3Allergy$1AlgyType$2;/*z/OS:infile'.prog2.rawdata(allergy)';*/infile'allergy.dat';inputIDLNameFNamePlanBloodAllergy@;ifAllergy='N'theninputDependents;elseifAllergy='Y'theninputAlgyTypeDependents;run;title1'PatientsandAllergyCode';procprintdata=allergies;run; 4.4SolutionstoExercises4-1576.SubsettingfromaRawDataFile(Optional)dataallergies2;lengthID$5LNameFName$11Plan$1Blood$3Allergy$1AlgyType$2;/*z/OS:infile'.prog2.rawdata(allergy)';*/infile'allergy.dat';inputIDLNameFNamePlanBloodAllergy@;ifAllergy='Y';inputAlgyTypeDependents;run;title1'PatientswithAllergiesOnly';procprintdata=allergies2;run;7.ReadingRawDatawithMultipleObservationsperRecord/*z/OS:fileref='.prog2.rawdata(transact)';*/procfslistfileref='transact.dat';run;datatransactions;lengthType$1;/*z/OS:infile'.prog2.rawdata(transact)';*/infile'transact.dat';inputDate:date9.TypeAmount:comma9.@@;run;title1'TransactionsonAccount';procprintdata=transactions;vardatetypeamount;run; 4-158Chapter4ReadingandWritingDifferentTypesofData8.CreatingMultipleSASDataSetsfromaSingleRawDataFile(Optional)/*z/OS:fileref='.prog2.rawdata(transact)';*/procfslistfileref='transact.dat';run;datacreditsdebits;lengthType$1;/*z/OS:infile'.prog2.rawdata(transact)';*/infile'transact.dat';inputDate:date9.TypeAmount:comma9.@@;ifType='C'thenoutputcredits;elseifType='D'thenoutputdebits;run;title1'CreditstoAccount';procprintdata=credits;vardatetypeamount;run;title1'DebitstoAccount';procprintdata=debits;vardatetypeamount;run;9.SubsettingfromaFixed-ColumnRawDataFile(Optional)/*z/OS:fileref='.prog2.rawdata(empfix)';*/procfslistfileref='empfix.dat';run;datasalclrks;/*z/OS:infile'.prog2.rawdata(empfix)';*/infile'empfix.dat';input@112JobCode$6.@;ifjobcode='SALCLK';input@1Division$20.@21HireDatemmddyy10.@31Salarydollar10.2@41LastName$15.@56FirstName$15.@71Country$15.@86Location$10.@96IdNumber$6.;run;title1'EmployeeInformationforSalesClerks';procprintdata=salclrksnoobs;run; 4.4SolutionstoExercises4-15910.UsingtheAbsoluteLinePointerControl(Optional)/*z/OS:fileref='.prog2.rawdata(emptwo)';*/procfslistfileref='emptwo.dat';run;dataempinfo;/*z/OS:infile'.prog2.rawdata(emptwo)'dlm=',';*/infile'emptwo.dat'dlm=',';input#2IdNumber:$6.LastName:$15.FirstName:$15.#1Division:$20.HireDate:mmddyy10.Salary;run;title1'EmployeeData';procprintdata=empinfo;formatHireDatemmddyy10.;run;11.ReadingaHierarchicalRawDataFileandCreatingOneObservationperDetailRecord/*z/OS:fileref='.prog2.rawdata(salaries)';*/procfslistfileref='salaries.dat';run;datasalaries(drop=type);retainIDLNameFName;lengthID$6;/*z/OS:infile'.prog2.rawdata(salaries)';*/infile'salaries.dat';inputType$@;ifType='E'theninputIDFName$LName$;elseifType='S'thendo;inputSalYearSalary:comma6.;output;end;run;title1'YearlySalariesThrough2001';procprintdata=salaries;run; 4-160Chapter4ReadingandWritingDifferentTypesofData12.ReadingaHierarchicalRawDataFileandCreatingOneObservationperHeaderRecord(Optional)/*z/OS:fileref='.prog2.rawdata(salaries)';*/procfslistfileref='salaries.dat';run;datacurrent(drop=SalYearType);/*Retainallthevariablesinthenewdataset.*/retainIDLNameFNameHireDateSalary;lengthID$6;/*z/OS:infile'.prog2.rawdata(salaries)'end=LastRec;*/infile'salaries.dat'end=LastRec;inputType$@;ifType='E'thendo;/*Outputwhennextemployeeisread.*/if_n_ne1thenoutput;inputID$FName$LName$HireDate:date9.;end;elseifType='S'thendo;inputSalYearSalary:comma8.;end;ifLastRecthenoutput;run;title1'Salariesasof2001';procprintdata=current;formatHireDatedate9.;run;13.ReadingaHierarchicalFileUsingTwoDATASteps(Optional)/*z/OS:fileref='.prog2.rawdata(salaries)';*/procfslistfileref='salaries.dat';run;datastepone(drop=SalYearType);retainIDLNameFNameHireDate;lengthID$6;/*z/OS:infile'.prog2.rawdata(salaries)';*/infile'salaries.dat';inputType$@;ifType='E'theninputID$FName$LName$HireDate:date9.;elseifType='S'theninputSalYear 4.4SolutionstoExercises4-161Salary:comma8.;formatHireDatedate9.;run;title1'ReadingaHierarchicalFile--FirstPhase';procprintdata=stepone;run;datatwostep;setstepone;byIDnotsorted;ifLast.IDthenoutput;run;title1'Salariesasof2001';procprintdata=twostep;run;14.ReadingaHierarchicalFilewithoutanExplicitIdentifyingField(Optional)/*z/OS:fileref='.prog2.rawdata(bstones)';*/procfslistfileref='bstones.dat';run;databirthstones;dropSpaceStone;retainMonthModernTraditionalMysticalAyurvedicOther1-Other3;/*z/OS:infile'.prog2.rawdata(bstones)'end=LastMonthdlm=',';*/infile'bstones.dat'end=LastMonthdlm=',';/*YoucanalsoreadthebirthstoneswithformattedinputifyouusetheTRUNCOVERorPADoption.*/lengthMonth$9ModernTraditional$12Mystical$11Ayurvedic$10Other1-Other3$15;input@1Space$1.@;/*Theleadingspacemustbereadwithformattedinput,orthespacewillbeignored.*/ifSpacene''thendo;if_n_ne1thenoutput;input@1Month$;Stone=1;other2='';other3='';end;/*Youneedtoknowhowmanydetailrecordshavebeenreadinordertoknowwhichvariableisbeingread.*/elsedo;ifStone=1theninputModern$; 4-162Chapter4ReadingandWritingDifferentTypesofDataelseifStone=2theninputTraditional;elseifStone=3theninputMystical;elseifStone=4theninputAyurvedic;elseifStone=5theninputOther1;elseifStone=6theninputOther2;elseifStone=7theninputOther3;Stone+1;end;ifLastMonththenoutput;run;title1'VariousBirthstonesforEachMonth';procprintdata=birthstones;run; Chapter5DataTransformations5.1Introduction.....................................................................................................................5-35.2ManipulatingCharacterValues.....................................................................................5-85.3ManipulatingNumericValues......................................................................................5-555.4ManipulatingNumericValuesBasedonDates..........................................................5-655.5ConvertingVariableType.............................................................................................5-705.6SolutionstoExercises.................................................................................................5-95 5-2Chapter5DataTransformations 5.1Introduction5-35.1IntroductionObjectives¢ReviewthesyntaxofSASfunctions.3SASFunctionsTheSASSystemprovidesalargelibraryoffunctionsformanipulatingdataduringDATAstepexecution.ASASfunctionisoftencategorizedbythetypeofdatamanipulationperformed:¢truncation¢special¢character¢samplestatistics¢dateandtime¢financial¢mathematical¢randomnumber¢trigonometric¢stateandzipcode4!SeeSASdocumentationforacompletelistoffunctionsandtheirsyntax. 5-4Chapter5DataTransformationsSyntaxforSASFunctionsASASfunctionisaroutinethatperformsacomputationorsystemmanipulationandreturnsavalue.Functionsuseargumentssuppliedbytheuserorbytheoperatingenvironment.GeneralformofaSASfunction:function-namefunction-name((argument-1argument-1,,argument-2argument-2,…,,…,argument-nargument-n))5UsingSASFunctionsYoucanusefunctionsinexecutableDATAstepstatementsanywherethatanexpressioncanappear.datacontrib;setprog2.donate;Total=sum(Qtr1,Qtr2,Qtr3,Qtr4);ifTotalge50;run;procprintdata=contribnoobs;run;6 5.1Introduction5-5UsingSASFunctionsPartialPROCPRINTOutputIDQtr1Qtr2Qtr3Qtr4TotalE00224123322.67E0036735484030153E00441.638990242E005871619302994E006211012152562WhatifyouwanttosumQtr1throughQtr400,insteadofQtr1throughQtr4?7 5-6Chapter5DataTransformationsSASVariableListsASASvariablelistisanabbreviatedmethodofreferringtoalistofvariablenames.SASenablesyoutousethefollowingvariablelists:¢numberedrangelists¢namerangelists¢nameprefixlists¢specialSASnamelists8specifiesallvariablesfromx1toxninclusive.YoucanbeginwithNumberedanynumberandendwithanynumberaslongasyoudonotviolatex1-xnrangeliststherulesforuser-suppliedvariablenamesandthenumbersareconsecutive.specifiesallvariablesorderedastheyareintheprogramdatax--avector,fromxtoainclusive.Namerangelistsx-numeric-aspecifiesallnumericvariablesfromxtoainclusive.x-character-aspecifiesallcharactervariablesfromxtoainclusive.NametellsSAStocalculatethesumofallthevariablesthatbeginwithsum(ofREV:)prefixlistsREV,suchasREVJAN,REVFEB,andREVMAR._ALL_specifiesallvariablesthatarealreadydefinedinthecurrentDATAstep.Special_NUMERIC_specifiesallnumericvariablesthatarecurrentlydefinedintheSASnamecurrentDATAstep.lists_CHARACTER_specifiesallcharactervariablesthatarecurrentlydefinedinthecurrentDATAstep. 5.1Introduction5-7SASVariableListsWhenyouuseaSASvariablelistinaSASfunction,usethekeywordOFinfrontofthefirstvariablenameinthelist.datacontrib;setprog2.donate;Total=sum(ofQtr1-Qtr4);ifTotalge50;run;IfyouomitthekeywordOF,subtractionisperformed.9 5-8Chapter5DataTransformations5.2ManipulatingCharacterValuesObjectives¢UseSASfunctionsandoperatorstoextract,edit,andsearchcharactervalues.11AMailingLabelApplicationTheprog2.freqflyersdatasetcontainsinformationaboutfrequentflyers.Usethisdatasettocreateanotherdatasetsuitableformailinglabels.12 5.2ManipulatingCharacterValues5-9AMailingLabelApplicationIDisacharactervariable.Itslastdigitrepresentsthegender(1denotesfemale,2denotesmale)ofthefrequentflyer.prog2.freqflyersIDNameAddress1Address2F31351Farr,Sue15HarveyRd.Macon,Bibb,GA,31298F161Cox,KayB.163McNeilPl.Kern,Pond,CA,93280F212Mason,Ron442GlenAve.Miami,Dade,FL,33054F25122Ruth,G.H.2491BradySt.Munger,Bay,MI,4874713AMailingLabelApplicationlabelsFullNameAddress1Address2Ms.SueFarr15HarveyRd.Macon,GA31298Ms.KayB.Cox163McNeilPl.Kern,CA93280Mr.RonMason442GlenAve.Miami,FL33054Mr.G.H.Ruth2491BradySt.Munger,MI48747ThefirsttaskistocreateatitleofMr.orMs.basedonthelastdigitofID.14 5-10Chapter5DataTransformationsTheSUBSTRFunction(RightSide)TheSUBSTRfunctionisusedtoextractorreplacecharacters.NewVarNewVar=SUBSTR(=SUBSTR(stringstring,,startstart<,<,length>length>));;ThisformoftheSUBSTRfunction(rightsideofassignmentstatement)extractscharacters.15stringcanbeacharacterconstant,variable,orexpression.startspecifiesthestartingposition.lengthspecifiesthenumberofcharacterstoextract.Ifomitted,thesubstringconsistsoftheremainderofstring.!IfthelengthofthecreatedvariableisnotpreviouslydefinedwithaLENGTHstatement,itisthesameasthelengthofthefirstargumenttoSUBSTR. 5.2ManipulatingCharacterValues5-11TheSUBSTRFunction(RightSide)ExtracttwocharactersfromLocationandstartatposition11.State=substr(Location,11,2);LocationState$18$18Columbus,OH43227OH16AMailingLabelApplicationprocprintdata=prog2.freqflyersnoobs;varID;run;PROCPRINTOutputIDF31351F161F212F25122InwhatpositiondoesthelastdigitofIDoccur?17 5-12Chapter5DataTransformationsTheRIGHTFunctionTheRIGHTfunctionreturnsitsargumentright-aligned.Trailingblanksaremovedtothestartofthevalue.NewVarNewVar=RIGHT(=RIGHT(argumentargument););IDNewID$6$6F161NewID=right(ID);F16118argumentcanbeacharacterconstant,variable,orexpression.!IfthelengthofthecreatedvariableisnotpreviouslydefinedwithaLENGTHstatement,itisthesameasthelengthofargument.TheLEFTfunctionreturnsitsargumentleft-aligned.Leadingblanksaremovedtotheendofthevalue.Theargument’slengthdoesnotchange.NewVar=LEFT(argument); 5.2ManipulatingCharacterValues5-13AMailingLabelApplicationdatalabels;setprog2.freqflyers;ifsubstr(right(ID),6)='1'thenTitle='Ms.';elseifsubstr(right(ID),6)='2'thenTitle='Mr.';run;procprintdata=labelsnoobs;varIDTitle;run;TheresultoftheRIGHTfunctionactsasthefirstargumenttotheSUBSTRfunction.19AMailingLabelApplicationPROCPRINTOutputIDTitleF31351Ms.F161Ms.F212Mr.F25122Mr.20 5-14Chapter5DataTransformationsAMailingLabelApplicationThenexttaskistoseparatethenamesofthefrequentflyersintotwoparts.NameFarr,SueCox,KayB.FMNameLNameSueFarrKayB.Cox21 5.2ManipulatingCharacterValues5-15TheSCANFunctionTheSCANfunctionreturnsthenthwordofacharactervalue.Itisusedtoextractwordsfromacharactervaluewhentherelativeorderofwordsisknown,buttheirstartingpositionsarenot.NewVarNewVar=SCAN(=SCAN(stringstring,,nn<,<,delimiters>delimiters>));;22stringcanbeacharacterconstant,variable,orexpression.nspecifiesthenthwordtoextractfromstring.delimitersdefinescharactersthatdelimit(separate)words.!Ifthethirdargumentisomitted,thedefaultdelimitersareASCII(PC,UNIX)blank.<(+|&!$*);-/,%^EBCDIC(z/OS)blank.<(+|&!$*);-/,%|¢¬ 5-16Chapter5DataTransformationsTheSCANFunctionWhentheSCANfunctionisused,¢thelengthofthecreatedvariableis200bytesifitisnotpreviouslydefinedwithaLENGTHstatement¢delimitersbeforethefirstwordhavenoeffect¢anycharacterorsetofcharacterscanserveasdelimiters¢twoormorecontiguousdelimitersaretreatedasasingledelimiter¢amissingvalueisreturnediftherearefewerthannwordsinstring¢ifnisnegative,SCANselectsthewordinthecharacterstringstartingfromtheendofstring.23TheSCANFunctionExtractthesecondwordofPhrase.Second=scan(Phrase,2,'');PhraseSecond$21$200softwareandservicesand12324 5.2ManipulatingCharacterValues5-17TheSCANFunctionExtractthesecondwordofPhrase.Second=scan(Phrase,2,':');PhraseSecond$21$200softwareand:servicesservices1225TheSCANFunctiondatascan;Text='(ThursdayJuly4,1776)';Var1=scan(Text,1);Var2=scan(Text,4);Var3=scan(Text,5);Var4=scan(Text,2,',');Var5=scan(Text,2,',)');run;26... 5-18Chapter5DataTransformationsTheSCANFunctiondatascan;1234Text='(ThursdayJuly4,1776)';Var1=scan(Text,1);Var2=scan(Text,4);Var3=scan(Text,5);Var4=scan(Text,2,',');Var5=scan(Text,2,',)');run;Var1$200Thursday27...TheSCANFunctiondatascan;1234Text='(ThursdayJuly4,1776)';Var1=scan(Text,1);Var2=scan(Text,4);Var3=scan(Text,5);Var4=scan(Text,2,',');Var5=scan(Text,2,',)');run;Var1Var2$200$200Thursday177628... 5.2ManipulatingCharacterValues5-19TheSCANFunctiondatascan;1234Text='(ThursdayJuly4,1776)';Var1=scan(Text,1);Var2=scan(Text,4);Var3=scan(Text,5);Var4=scan(Text,2,',');Var5=scan(Text,2,',)');run;Var1Var2Var3$200$200$200Thursday1776missing29...TheSCANFunctiondatascan;12Text='(ThursdayJuly4,1776)';Var1=scan(Text,1);Var2=scan(Text,4);Var3=scan(Text,5);Var4=scan(Text,2,',');Var5=scan(Text,2,',)');run;Var1Var2Var3Var4$200$200$200$200Thursday17761776)space30... 5-20Chapter5DataTransformationsTheSCANFunctiondatascan;12Text='(ThursdayJuly4,1776)';Var1=scan(Text,1);Var2=scan(Text,4);Var3=scan(Text,5);Var4=scan(Text,2,',');Var5=scan(Text,2,',)');run;Var1Var2Var3Var4Var5$200$200$200$200$200Thursday17761776)1776space31AMailingLabelApplicationdatalabels;lengthFMNameLName$10;setprog2.freqflyers;ifsubstr(right(ID),6)='1'thenTitle='Ms.';elseifsubstr(right(ID),6)='2'thenTitle='Mr.';FMName=scan(Name,2,',');LName=scan(Name,1,',');run;32 5.2ManipulatingCharacterValues5-21AMailingLabelApplicationprocprintdata=labelsnoobs;varIDNameTitleFMNameLName;run;PROCPRINTOutputIDNameTitleFMNameLNameF31351Farr,SueMs.SueFarrF161Cox,KayB.Ms.KayB.CoxF212Mason,RonMr.RonMasonF25122Ruth,G.H.Mr.G.H.RuthThenexttaskistojointhevaluesofTitle,FMName,andLNameintoanothervariable.33 5-22Chapter5DataTransformationsConcatenationOperatorTheconcatenationoperatorjoinscharacterstrings.Dependingonthecharactersavailableonyourkeyboard,thesymboltoconcatenatecharactervaluescanbetwoexclamationpoints(!!),twoverticalbars(||),ortwobrokenverticalbars(¦¦).NewVarNewVar==string1string1!!!!string2string2;;34ConcatenationOperatorCombineFMNameandLNametocreateFullName.FullName=FMName!!LName;FMNameLNameFullName$10$10$20SueFarrSueFarr35 5.2ManipulatingCharacterValues5-23TheTRIMFunctionTheTRIMfunctionremovestrailingblanksfromitsargument.NewVarNewVar=TRIM(=TRIM(argument1argument1)!!)!!argument2argument2;;Iftheargumentisblank,TRIMreturnsoneblank.36argument1andargument2canbecharacterconstants,variables,orexpressions.!TheTRIMandTRIMNfunctionsaresimilar.TRIMNreturnsanullstring(zeroblanks)iftheargumentisblank.TheCOMPBLfunctionisalsousedtoremovemultipleblanksinacharacterstring.COMPBLtranslateseachoccurrenceoftwoormoreconsecutiveblanksintoasingleblank.Bydefault,thelengthofthevaluereturnedbytheCOMPBLfunctionisthesameasthelengthoftheargument. 5-24Chapter5DataTransformationsTheTRIMFunctiondatatrim;lengthFMNameLName$10;FMName='Sue';LName='Farr';FullName1=trim(FMName);FullName2=trim(FMName)!!LName;FullName3=trim(FMName)!!''!!LName;run;FullName1$10Sue37...TheTRIMFunctiondatatrim;lengthFMNameLName$10;FMName='Sue';LName='Farr';FullName1=trim(FMName);FullName2=trim(FMName)!!LName;FullName3=trim(FMName)!!''!!LName;run;FullName1FullName2$10$20SueSueFarr38... 5.2ManipulatingCharacterValues5-25TheTRIMFunctiondatatrim;lengthFMNameLName$10;FMName='Sue';LName='Farr';FullName1=trim(FMName);FullName2=trim(FMName)!!LName;FullName3=trim(FMName)!!''!!LName;run;FullName1FullName2FullName3$10$20$21SueSueFarrSueFarr39TheTRIMfunctiondoesnotremoveleadingblanksfromacharacterargument.UseacombinationoftheTRIMandLEFTfunctionstoremoveleadingandtrailingblanksfromacharacterargument.Forexample,ifFMNamecontainedleadingblanks,thefollowingassignmentstatementwouldcorrectlyconcatenateFMNameandLNameintoFullName:FullName=trim(left(FMName))!!''!!LName; 5-26Chapter5DataTransformationsAMailingLabelApplicationdatalabels(keep=FullNameAddress1Address2);lengthFMNameLName$10;setprog2.freqflyers;ifsubstr(right(ID),6)='1'thenTitle='Ms.';elseifsubstr(right(ID),6)='2'thenTitle='Mr.';FMName=scan(Name,2,',');LName=scan(Name,1,',');FullName=Title!!''!!trim(FMName)!!''!!LName;Address2=scan(Address2,1,',')!!','!!scan(Address2,3,',')!!''!!scan(Address2,4,',');run;40AMailingLabelApplicationprocprintdata=labelsnoobs;varFullNameAddress1Address2;run;PROCPRINTOutputFullNameAddress1Address2Ms.SueFarr15HarveyRd.Macon,GA31298Ms.KayB.Cox163McNeilPl.Kern,CA93280Mr.RonMason442GlenAve.Miami,FL33054Mr.G.H.Ruth2491BradySt.Munger,MI48747c05s2d1.sas41 5.2ManipulatingCharacterValues5-27TheCATXFunctionTheCATXfunctionconcatenatescharacterstrings,removesleadingandtrailingblanks,andinsertsseparators.CATXCATX((separatorseparator,,string-1,string-1,……,string-n,string-n))!CATXisaSAS®9function.42®OtherSAS9concatenationfunctionsareasfollows:CATconcatenatescharacterstringswithoutremovingleadingortrailingblanks.CATSconcatenatescharacterstringsandremovesleadingandtrailingblanks.CATTconcatenatescharacterstringsandremovestrailingblanksonly.!Caution:Thelengthreturnedbythesefunctionsisupto•200bytesinWHEREclausesandinPROCSQL•32767bytesinaDATAstep(exceptaWHEREstatement)•65534byteswhenthestringiscalledfromthemacroprocessor. 5-28Chapter5DataTransformationsAMailingLabelApplicationdatalabels(keep=FullNameAddress1Address2);lengthFMNameLName$10;setprog2.freqflyers;ifsubstr(right(ID),6)='1'thenTitle='Ms.';elseifsubstr(right(ID),6)='2'thenTitle='Mr.';FMName=scan(Name,2,',');LName=scan(Name,1,',');FullName=catx('',Title,FMName,LName);Address2=catx('',scan(Address2,1,',')!!',',scan(Address2,3,','),scan(Address2,4,','));run;43AMailingLabelApplicationprocprintdata=labelsnoobs;varFullNameAddress1Address2;run;PROCPRINTOutputFullNameAddress1Address2Ms.SueFarr15HarveyRd.Macon,GA31298Ms.KayB.Cox163McNeilPl.Kern,CA93280Mr.RonMason442GlenAve.Miami,FL33054Mr.G.H.Ruth2491BradySt.Munger,MI48747c05s2d2.sas44 5.2ManipulatingCharacterValues5-29Exercises1.ManipulatingCharacterValuesAllvaluesofNameinprog2.peopleconsistofalastname,firstname,andmiddleinitial.Listingofprog2.peopleNameCityStateDEAN,LINDSAYA.WILMINGTON,NCFLORENTINO,HELEN-ASHEH.WASHINGTON,DCVANALLSBURG,JANF.SHORTHILLS,NJLAFF,STANLEYX.SPRINGFIELD,ILRIZEN,GEORGEQ.CHICAGO,ILMITCHELL,MARCJ.CHICAGO,ILMILLS,DOROTHYE.JOE,MTWEBB,JONATHANW.MORRISVILLE,NCKEENAN,MAYNARDJ.SEDONA,AZLACK,PHYLLISM.WALTHAM,MATHOMPSON,KERRYL.WINTERPARK,FLCOX,DOROTHYE.TIMONIUM,MDSEPTOFF,DONALDE.BOSTON,MAPHOENIX,JANICEA.SOMERVILLE,NJHUNEYCUTT,MURRAYY.DIMEBOX,TXERICKSON,SHERRYA.ELPASO,TXSCHNEIDER,CLIVEJ.CAPEMAY,NJPUTNAM,KIMBERLYM.DUNWOODY,GAPITTMAN,JENNIFERR.BENNINGTON,VTROLEN,STACYD.CODY,WY!Somenamescontainhyphenatedfirstnamesormultiple-wordlastnames.ReadthevariablesNameandCityStatefromprog2.peopletocreateatemporarySASdatasetnamedseparatethatcontainsthevariablesFirst,MI,andLast.Payspecialattentiontotrailingandleadingblanks,andthelengthsofFirst,MI,andLast.!TocreateFirstandMI,createavariablethatcontainseachperson’sfirstnameandmiddleinitial.Donotincludethisvariableintheseparatedataset.Printtheseparatedatasettoverifyyourresults.PartialListingofseparateObsNameCityStateFirstMILast1DEAN,LINDSAYA.WILMINGTON,NCLINDSAYA.DEAN2FLORENTINO,HELEN-ASHEH.WASHINGTON,DCHELEN-ASHEH.FLORENTINO3VANALLSBURG,JANF.SHORTHILLS,NJJANF.VANALLSBURG4LAFF,STANLEYX.SPRINGFIELD,ILSTANLEYX.LAFF5RIZEN,GEORGEQ.CHICAGO,ILGEORGEQ.RIZEN 5-30Chapter5DataTransformations2.CombiningCharacterValuesUsetheDATAstepthatcreatesseparatetocreateatemporarySASdatasetnamedflnamethatcontainsthevariablesNewNameandCityState.ThevaluesofNewNameshouldbetheconcatenationofeachperson’sfirstnameandlastnamewithasingleblankbetweenthem.PartialListingofprog2.peopleNameCityStateDEAN,LINDSAYA.WILMINGTON,NCFLORENTINO,HELEN-ASHEH.WASHINGTON,DCVANALLSBURG,JANF.SHORTHILLS,NJLAFF,STANLEYX.SPRINGFIELD,ILRIZEN,GEORGEQ.CHICAGO,IL!Somenamescontainhyphenatedfirstnamesormultiple-wordlastnames.Printtheflnamedatasettoverifyyourresults.PartialListingofflnameObsNewNameCityState1LINDSAYDEANWILMINGTON,NC2HELEN-ASHEFLORENTINOWASHINGTON,DC3JANVANALLSBURGSHORTHILLS,NJ4STANLEYLAFFSPRINGFIELD,IL5GEORGERIZENCHICAGO,IL3.PerformingAdditionalCharacterManipulations(Optional)UsetheDATAstepthatcreatesseparatetocreateatemporarySASdatasetnamedinitthatcontainsthevariablesName,Initials,andCityState.ThevaluesofInitialsshouldbetheconcatenationofthefirstcharacterfromeachperson’sfirstname,middlename,andlastnamewithnodelimitersseparatingthecharacters.Printtheinitdatasettoverifyyourresults.PartialListingofinitObsNameCityStateInitials1DEAN,LINDSAYA.WILMINGTON,NCLAD2FLORENTINO,HELEN-ASHEH.WASHINGTON,DCHHF3VANALLSBURG,JANF.SHORTHILLS,NJJFV4LAFF,STANLEYX.SPRINGFIELD,ILSXL5RIZEN,GEORGEQ.CHICAGO,ILGQR 5.2ManipulatingCharacterValues5-31ASearchApplicationTheprog2.ffhistorydatasetcontainsinformationaboutthehistoryofeachfrequentflyer.Thishistoryinformationconsistsof¢eachmembershiplevelthattheflyerattained(bronze,silver,orgold)¢theyearthattheflyerattainedeachlevel.Createareportthatshowsallfrequentflyerswhoattainedsilvermembershipstatusandtheyeareachofthembecamesilvermembers.46ASearchApplicationprog2.ffhistorySeatIDStatusPrefF31351Silver1998,Gold2000AISLEF161Bronze1999WINDOWF212Bronze1992,silver1995WINDOWF25122Bronze1994,Gold1996,Silver1998AISLETodeterminewhoattainedsilvermembershipstatus,youmustsearchtheStatusvariableforthevalue"Silver".47 5-32Chapter5DataTransformationsTheFINDFunctionTheFINDfunctionsearchesforaspecificsubstringofcharacterswithinacharacterstringthatyouspecifyandreturnsitslocation.PositionPosition=FIND(=FIND(targettarget,,value<,modifiers,startpos>value<,modifiers,startpos>));;TheFINDfunctionreturns¢thestartingpositionofthefirstoccurrenceofvaluewithintarget,ifvalueisfound¢0,ifvalueisnotfound.!FINDisaSAS®9function.48AmodifiercanbethevalueIorT.Iindicatesthatthesearchiscase-insensitive.Tindicatesthatthesearchignorestrailingblanks.Thesetwovaluescanbecombinedineitherorderandineithercase.Ifthisargumentisomitted,thesearchiscase-sensitiveandtrailingblanksaretakenintoconsideration.Thestartposisanintegerthatspecifiesthepositionatwhichthesearchshouldstartandthedirectionofthesearch.Apositivevalueindicatesaforward(right)search.Anegativevalueindicatesabackward(left)search.Ifthisargumentisomitted,thesearchstartsatposition1andmovesforward.Thesetwooptionalargumentscanbeineitherorder(thatis,startposcanprecedemodifier). 5.2ManipulatingCharacterValues5-33TheFINDFunctionDeterminewhetherTextcontainsthestring"BULL'S-EYE".Text="ThistargetcontainsaBULL'S-EYE.";Pos=find(Text,"BULL'S-EYE");24TextPos$34N8ThistargetcontainsaBULL'S-EYE.2449TheFINDFunction6dataindex;Text='DELIMITITWITHBLANKS.';Pos1=find(Text,'IT');Pos2=find(Text,'IT');Pos3=find(Text,'it');Pos4=find(Text,'it','I');run;Pos1N8650... 5-34Chapter5DataTransformationsTheFINDFunction8dataindex;Text='DELIMITITWITHBLANKS.';Pos1=find(Text,'IT');Pos2=find(Text,'IT');Pos3=find(Text,'it');Pos4=find(Text,'it','I');run;Pos1Pos2N8N86851...TheFINDFunctiondataindex;Text='DELIMITITWITHBLANKS.';Pos1=find(Text,'IT');Pos2=find(Text,'IT');Pos3=find(Text,'it');Pos4=find(Text,'it','I');run;Pos1Pos2Pos3N8N8N868052... 5.2ManipulatingCharacterValues5-35TheFINDFunction6dataindex;Text='DELIMITITWITHBLANKS.';Pos1=find(Text,'IT');Pos2=find(Text,'IT');Pos3=find(Text,'it');Pos4=find(Text,'it','I');run;Pos1Pos2Pos3Pos4N8N8N8N8680653...TheFINDFunction8dataindex2;lengthString$5;String='IT';Text='DELIMITITWITHBLANKS.';Pos5=find(Text,String);Pos6=find(Text,String,'T');Pos7=find(Text,''!!trim(String)!!'');run;StringPos5Pos6Pos7$5N8N8N8IT06856 5-36Chapter5DataTransformationsASearchApplicationprog2.ffhistorySeatIDStatusPrefF31351Silver1998,Gold2000AISLEF161Bronze1999WINDOWF212Bronze1992,silver1995WINDOWF25122Bronze1994,Gold1996,Silver1998AISLEdatasilver;setprog2.ffhistory;iffind(Status,'silver','I')>0;run;57ASearchApplicationprocprintdata=silvernoobs;run;PROCPRINTOutputSeatIDStatusPrefF31351Silver1998,Gold2000AISLEF212Bronze1992,silver1995WINDOWF25122Bronze1994,Gold1996,Silver1998AISLE58 5.2ManipulatingCharacterValues5-37TheINDEXFunctionTheINDEXfunctionsearchesacharacterargumentforthelocationofaspecifiedcharactervalueandreturnsitslocation.PositionPosition=INDEX(=INDEX(targettarget,,valuevalue));;TheINDEXfunctionreturns¢thestartingpositionofthefirstoccurrenceofvaluewithintarget,ifvalueisfound¢0,ifvalueisnotfound.59targetspecifiesthecharacterexpressiontosearch.valuespecifiesthestringofcharacterstosearchforinthecharacterexpression.!Thesearchforvalueisliteral.Capitalizationandblanks(leading,embedded,andtrailing)areconsidered.INDEXdiffersfromFINDinthatitdoesnothavemodifierorstartposfunctionality. 5-38Chapter5DataTransformationsTheINDEXFunctionDeterminewhetherTextcontainsthestring"BULL'S-EYE".Text="ThistargetcontainsaBULL'S-EYE.";Pos=index(Text,"BULL'S-EYE");24TextPos$34N8ThistargetcontainsaBULL'S-EYE.2460TheINDEXFunctiondataindex;6Text='DELIMITITWITHBLANKS.';Pos1=index(Text,'IT');Pos2=index(Text,'IT');Pos3=index(Text,'it');run;Pos1N8661... 5.2ManipulatingCharacterValues5-39TheINDEXFunction8dataindex;Text='DELIMITITWITHBLANKS.';Pos1=index(Text,'IT');Pos2=index(Text,'IT');Pos3=index(Text,'it');run;Pos1Pos2N8N86862...TheINDEXFunctiondataindex;Text='DELIMITITWITHBLANKS.';Pos1=index(Text,'IT');Pos2=index(Text,'IT');Pos3=index(Text,'it');run;Pos1Pos2Pos3N8N8N868063... 5-40Chapter5DataTransformationsTheINDEXFunctiondataindex2;lengthString$5;String='IT';Text='DELIMITITWITHBLANKS.';Pos4=index(Text,String);Pos5=index(Text,trim(String));Pos6=index(Text,''!!trim(String)!!'');run;String$5IT64...TheINDEXFunctiondataindex2;lengthString$5;String='IT';Text='DELIMITITWITHBLANKS.';Pos4=index(Text,String);Pos5=index(Text,trim(String));Pos6=index(Text,''!!trim(String)!!'');run;StringPos4$5N8IT065... 5.2ManipulatingCharacterValues5-41TheINDEXFunctiondataindex2;6lengthString$5;String='IT';Text='DELIMITITWITHBLANKS.';Pos4=index(Text,String);Pos5=index(Text,trim(String));Pos6=index(Text,''!!trim(String)!!'');run;StringPos4Pos5$5N8N8IT0666...TheINDEXFunctiondataindex2;8lengthString$5;String='IT';Text='DELIMITITWITHBLANKS.';Pos4=index(Text,String);Pos5=index(Text,trim(String));Pos6=index(Text,''!!trim(String)!!'');run;StringPos4Pos5Pos6$5N8N8N8IT06867 5-42Chapter5DataTransformationsASearchApplicationprog2.ffhistorySeatIDStatusPrefF31351Silver1998,Gold2000AISLEF161Bronze1999WINDOWF212Bronze1992,silver1995WINDOWF25122Bronze1994,Gold1996,Silver1998AISLEdatasilver;setprog2.ffhistory;ifindex(Status,'Silver')>0;run;68ASearchApplicationprocprintdata=silvernoobs;run;PROCPRINTOutputSeatIDStatusPrefF31351Silver1998,Gold2000AISLEF25122Bronze1994,Gold1996,Silver1998AISLEWhywasF212notselected?69 5.2ManipulatingCharacterValues5-43TheUPCASEFunctionTheUPCASEfunction¢convertsalllettersinitsargumenttouppercase¢hasnoeffectondigitsandspecialcharacters.NewValNewVal=UPCASE(=UPCASE(argumentargument));;70ASearchApplicationdatasilver(drop=Location);lengthYear$4;setprog2.ffhistory;Location=index(upcase(Status),'SILVER');ifLocation>0;Year=substr(Status,Location+7,4);run;procprintdata=silvernoobs;varIDStatusYearSeatPref;run;71 5-44Chapter5DataTransformationsASearchApplicationYear=substr(Status,Location+7,4);PROCPRINTOutputLocationLocation+7SeatIDStatusYearPrefF31351Silver1998,Gold20001998AISLEF212Bronze1992,silver19951995WINDOWF25122Bronze1994,Gold1996,Silver19981998AISLEDidthecapitalizationofthevaluesofStatuspermanentlychange?72ThePROPCASEFunctionThePROPCASEfunctionconvertsallwordsinanargumenttopropercase,inwhichthefirstletterisuppercaseandtheremaininglettersarelowercase.NewValNewVal=PROPCASE(=PROPCASE(argumentargument<,<,delimiter(s)delimiter(s)>)>);;!PROPCASEisaSAS®9function.73Delimitersarecharacterswhichseparatewords.ThedefaultdelimitersforthePROPCASEfunctionaretheblank,forwardslash,hyphen,openparenthesis,period,andtabcharacters. 5.2ManipulatingCharacterValues5-45ASearchApplicationdatasilver(drop=Location);lengthYear$4;setprog2.ffhistory;Status=propcase(Status,',');Location=find(Status,'Silver');ifLocation>0;SeatPref=propcase(SeatPref);Year=substr(Status,Location+7,4);run;procprintdata=silvernoobs;varIDStatusYearSeatPref;run;c05s2d3.sas74ASearchApplicationPROCPRINTOutputSeatIDStatusYearPrefF31351Silver1998,Gold20001998AisleF212Bronze1992,Silver19951995WindowF25122Bronze1994,Gold1996,Silver19981998Aisle75 5-46Chapter5DataTransformationsTheTRANWRDFunctionTheTRANWRDfunctionreplacesorremovesalloccurrencesofagivenword(orapatternofcharacters)withinacharacterstring.NewValNewVal=TRANWRD(=TRANWRD(sourcesource,,targettarget,,replacementreplacement));;TheTRANWRDfunctiondoesnotremovetrailingblanksfromtargetorreplacement.76sourcespecifiesthesourcestringthatyouwanttotranslate.targetspecifiesthestringsearchedforinsource.replacementspecifiesthestringthatreplacestarget.!IfthelengthofthecreatedvariableisnotpreviouslydefinedwithaLENGTHstatement,itis200bytes. 5.2ManipulatingCharacterValues5-47TheTRANWRDFunctionReplacethefirstwordofDessert.Dessert=tranwrd(Dessert,'Pumpkin','Apple');DessertDessert$20$20PumpkinpieApplepie77UsingtheTRANWRDfunctiontoreplaceanexistingstringwithalongerstringmightcausetruncationoftheresultingvalueifaLENGTHstatementisnotused.ASearchApplicationdatasilver(drop=Location);lengthYear$4;setprog2.ffhistory;Status=tranwrd(Status,'silver','Silver');Location=index(Status,'Silver');ifLocation>0;Year=substr(Status,Location+7,4);run;procprintdata=silvernoobs;varIDStatusYearSeatPref;run;c05s2d4.sas78 5-48Chapter5DataTransformationsASearchApplicationPROCPRINTOutputSeatIDStatusYearPrefF31351Silver1998,Gold20001998AISLEF212Bronze1992,Silver19951995WINDOWF25122Bronze1994,Gold1996,Silver19981998AISLE79TheLOWCASEFunctionTheLOWCASEfunction¢convertsalllettersinitsargumenttolowercase¢hasnoeffectondigitsandspecialcharacters.NewValNewVal=LOWCASE(=LOWCASE(argumentargument));;80argumentspecifiesanycharacterargument. 5.2ManipulatingCharacterValues5-49TheSUBSTRFunction(LeftSide)TheSUBSTRfunctionisusedtoextractorreplacecharacters.SUBSTR(SUBSTR(stringstring,,startstart<,<,lengthlength>)=>)=valuevalue;;ThisformoftheSUBSTRfunction(leftsideofassignmentstatement)replacescharactersinacharactervariable.81stringspecifiesacharactervariable.startspecifiesanumericexpressionthatisthebeginningcharacterposition.lengthspecifiesanumericexpressionthatisthelengthofthesubstringthatwillbereplaced.!Thelengthvaluecannotbelargerthantheremaininglengthofstring(includingtrailingblanks)afterstart.Ifyouomitlength,SASusesallofthecharactersontherightsideoftheassignmentstatementtoreplacethevaluesofstring,uptothelimitindicatedbythepreviousnote. 5-50Chapter5DataTransformationsTheSUBSTRFunction(LeftSide)ReplacetwocharactersfromLocationstartingatposition11.substr(Location,11,2)='OH';LocationLocation$18$18Columbus,GA43227Columbus,OH4322782TheLOWCASEFunctiondatasilver;setsilver;substr(SeatPref,2)=lowcase(substr(SeatPref,2));run;SeatPref$6AISLEc05s2d5.sas83... 5.2ManipulatingCharacterValues5-51TheLOWCASEFunctiondatasilver;setsilver;substr(SeatPref,2)=lowcase(substr(SeatPref,2));run;SeatPref$6AISLEislec05s2d5.sas84...TheLOWCASEFunctiondatasilver;setsilver;substr(SeatPref,2)=lowcase(substr(SeatPref,2));run;SeatPrefSeatPref$6$6AISLEAisleislec05s2d5.sas85 5-52Chapter5DataTransformationsASearchApplicationprocprintdata=silvernoobs;varIDYearSeatPref;run;PROCPRINTOutputSeatIDYearPrefF313511998AisleF2121995WindowF251221998Aisle86 5.2ManipulatingCharacterValues5-53Exercises4.SearchingforaCharacterValueReadthevariablesNameandCityStatefromprog2.peopletocreateatemporarySASdatasetnamedprairiethatcontainsonlythosepeoplewholiveinthestateofIllinois(IL).UseanappropriatefunctiontosearchthroughthevaluesofCityState.PartialListingofprog2.peopleNameCityStateDEAN,LINDSAYA.WILMINGTON,NCFLORENTINO,HELEN-ASHEH.WASHINGTON,DCVANALLSBURG,JANF.SHORTHILLS,NJLAFF,STANLEYX.SPRINGFIELD,ILRIZEN,GEORGEQ.CHICAGO,ILPrinttheprairiedatasettoverifyyourresults.Thereshouldbethreeobservations.ListingofprairieObsNameCityState1LAFF,STANLEYX.SPRINGFIELD,IL2RIZEN,GEORGEQ.CHICAGO,IL3MITCHELL,MARCJ.CHICAGO,IL!IllinoisisunofficiallyknownasthePrairieState.ThisnicknameoriginatesfromthepracticeofdeclaringthethirdfullweekinSeptembereachyearasIllinoisPrairieWeektodemonstratethevalueofpreservingandre-establishingnativeIllinoisprairies.5.PerformingAdditionalCharacterManipulationsReadthevariablesNameandCityStatefromprairietocreateatemporarySASdatasetnamedmixedprairiethatcontainsthevaluesofNameconvertedfromalluppercasetomixedcaseasshownbelow.Printthemixedprairiedatasettoverifyyourresults.ListingofmixedprairieObsNameCityState1Laff,StanleyX.SPRINGFIELD,IL2Rizen,GeorgeQ.CHICAGO,IL3Mitchell,MarcJ.CHICAGO,IL 5-54Chapter5DataTransformations6.UsingAdditionalCharacterFunctionsReadthevariablesNameandCityStatefromprog2.peopletocreateatemporarySASdatasetnamedstatelong.UsetheSTNAMELfunctiontoconvertthestatepostalcodeinCityStatetothecorrespondingstatename.StorethesestatenamesinavariablenamedStateName.TheSTNAMELfunctionconvertsatwo-characterstatepostalcode(orworld-wideGSAgeographiccodeforU.S.territories),suchasILforIllinois,tothecorrespondingstatenameinmixedcase.Returnedvaluescancontainupto20characters.NewState=STNAMEL(postal-code);postal-codespecifiesacharacterexpressionthatcontainsthetwo-characterstandardstatepostalcode.Characterscanbemixedcase.!STNAMELignorestrailingblanksbutgeneratesanerroriftheexpressioncontainsleadingblanks.PartialListingofstatelongObsNameStateName1DEAN,LINDSAYA.NorthCarolina2FLORENTINO,HELEN-ASHEH.DistrictofColumbia3VANALLSBURG,JANF.NewJersey4LAFF,STANLEYX.Illinois5RIZEN,GEORGEQ.Illinois7.PerformingAdditionalCharacterManipulations(Optional)ReadthevariablesNameandCityStatefromprog2.peopletocreateatemporarySASdatasetnamedmixedallthatcontainsthevaluesofNameconvertedfromalluppercasetomixedcaseasshownbelow.Printthemixedalldatasettoverifyyourresults.PartialListingofmixedallObsNameCityState1Dean,LindsayA.WILMINGTON,NC2Florentino,Helen-AsheH.WASHINGTON,DC3VanAllsburg,JanF.SHORTHILLS,NJ4Laff,StanleyX.SPRINGFIELD,IL5Rizen,GeorgeQ.CHICAGO,IL!Somenamescontainhyphenatedfirstnamesormultiple-wordlastnames. 5.3ManipulatingNumericValues5-555.3ManipulatingNumericValuesObjectives¢UseSASfunctionstotruncatenumericvalues.¢UseSASfunctionstocomputesamplestatisticsofnumericvalues.89TruncationFunctionsSelectedfunctionsthattruncatenumericvaluesinclude¢ROUNDfunction¢CEILfunction¢FLOORfunction¢INTfunction.90 5-56Chapter5DataTransformationsTheROUNDFunctionTheROUNDfunctionreturnsavalueroundedtothenearestround-offunit.NewVarNewVar=ROUND(=ROUND(argumentargument<,<,round-off-unitround-off-unit>)>);;Ifround-off-unitisnotprovided,argumentisroundedtothenearestinteger.91argumentisnumeric.round-off-unitisnumericandpositive.TheROUNDFunctiondatatruncate;NewVar1=round(12.12);NewVar2=round(42.65,.1);NewVar3=round(6.478,.01);NewVar4=round(96.47,10);run;NewVar1NewVar2NewVar3NewVar41242.76.4810095 5.3ManipulatingNumericValues5-57TheCEILFunctionTheCEILfunctionreturnsthesmallestintegergreaterthanorequaltotheargument.NewVarNewVar=CEIL(=CEIL(argumentargument));;345X4.4x=ceil(4.4);96argumentisnumeric.TheFLOORFunctionTheFLOORfunctionreturnsthegreatestintegerlessthanorequaltotheargument.NewVarNewVar=FLOOR(=FLOOR(argumentargument));;345X3.6y=floor(3.6);97argumentisnumeric. 5-58Chapter5DataTransformationsTheINTFunctionTheINTfunctionreturnstheintegerportionoftheargument.NewVarNewVar=INT(=INT(argumentargument));;345X3.9z=int(3.9);98argumentisnumeric.TruncationFunctionsdatatruncate;Var1=6.478;NewVar1=ceil(Var1);NewVar2=floor(Var1);NewVar3=int(Var1);run;Var1NewVar1NewVar2NewVar36.478766101 5.3ManipulatingNumericValues5-59TruncationFunctionsUsethesamefunctionswithanegativevalueforthevariableVar1.datatruncate;Var1=-6.478;NewVar1=ceil(Var1);NewVar2=floor(Var1);NewVar3=int(Var1);run;Var1NewVar1NewVar2NewVar3-6.478-6-7-6104!Forvaluesgreaterthan0,FLOORandINTreturnthesamevalue.Forvalueslessthan0,CEILandINTreturnthesamevalue. 5-60Chapter5DataTransformationsFunctionsThatComputeStatisticsSelectedfunctionsthatcomputesamplestatisticsbasedonagroupofvalues:¢SUMfunction(totalofvalues)¢MEANfunction(averageofvalues)¢MINfunction(lowestvalue)¢MAXfunction(highestvalue)105Thesefunctions•acceptmultipleargumentsinanyorder•usethesamealgorithmasSASstatisticalprocedures•ignoremissingvalues.TheMINfunctionreturnsthesmallestnon-missingvalue:MIN(argument-1,argument-2,…,argument-n)TheMAXfunctionreturnsthelargestvalue:MAX(argument-1,argument-2,…,argument-n)argument-1throughargument-narenumeric.Atleasttwoargumentsarerequired.Theargumentlistmightconsistofavariablelist,whichisprecededbyOF. 5.3ManipulatingNumericValues5-61TheSUMFunctionTheSUMfunctionaddsvaluestogetherandignoresmissingvalues.NewVarNewVar=SUM(=SUM(argument-1argument-1,,argument-2argument-2,,……,,argument-nargument-n));;106argument-1throughargument-narenumeric.TheSUMFunctiondatasummary;Var1=12;Var2=.;Var3=6;NewVar=sum(Var1,Var2,Var3);run;Var1Var2Var3NewVar12.618107... 5-62Chapter5DataTransformationsTheSUMFunctiondatasummary;Var1=12;Var2=.;Var3=6;NewVar=sum(Var1,Var2,Var3);run;Var1Var2Var3NewVar12.618WhatwouldbethevalueofNewVarifanarithmeticoperatorwasusedinsteadoftheSUMfunction?108...!TheassignmentstatementcanberewrittentotakeadvantageofSASvariablelists:NewVar=sum(ofVar1-Var3);TheSUMFunctiondatasummary;Var1=12;Var2=.;Var3=6;NewVar=Var1+Var2+Var3;run;Var1Var2Var3NewVar12.6.109 5.3ManipulatingNumericValues5-63TheMEANFunctionTheMEANfunctioncalculatesthearithmeticmean(average)ofvaluesandignoresmissingvalues.NewVarNewVar=MEAN(=MEAN(argument-1argument-1,,argument-2argument-2,,……,,argument-nargument-n));;110argument-1throughargument-narenumeric.TheMEANFunctiondatasummary;Var1=12;Var2=.;Var3=6;NewVar=mean(Var1,Var2,Var3);run;Var1Var2Var3NewVar12.69111!TheassignmentstatementcanberewrittentotakeadvantageofSASvariablelists:NewVar=mean(ofVar1-Var3); 5-64Chapter5DataTransformationsExercises8.ManipulatingNumericValuesCreateadatasetnamedfinalfromprog2.grade.ThefinaldatasetshouldcontainanewvariableOverallthatisthesemesteraveragegrade.CalculateOverallbyaveragingallthetestsplusthefinal.Thefinalisweightedtwiceasmuchasanyoftheothertests,socountthefinaltwicewhencalculatingOverall.StoreOverallroundedtothenearestinteger.Printthefinaldataset.PartialListingofprog2.gradeSSNCourseTest1Test2Test3Final012-40-4928BUS45080708080012-83-3816BUS45090906080341-44-0781MATH40078879091423-01-7721BUS45080707595448-23-8111MATH400889110095PartialListingoffinalObsSSNCourseTest1Test2Test3FinalOverall1012-40-4928BUS45080708080782012-83-3816BUS45090906080803341-44-0781MATH40078879091874423-01-7721BUS45080707595835448-23-8111MATH400889110095949.PerformingAdditionalNumericManipulations(Optional)ModifytheDATAstepcreatedinthepreviousexercisesothatthevalueofOverallistheaverageofthetwohighesttestscoresandthefinal.(ThelowesttestscoreshouldnotbeusedtocalculateOverall.)Asbefore,thefinalshouldbecountedtwice.StoreOverallroundedtothenearestinteger.Printthefinaldataset.PartialListingoffinalObsSSNCourseTest1Test2Test3FinalOverall1012-40-4928BUS45080708080802012-83-3816BUS45090906080853341-44-0781MATH40078879091904423-01-7721BUS45080707595865448-23-8111MATH40088911009595 5.4ManipulatingNumericValuesBasedonDates5-655.4ManipulatingNumericValuesBasedonDatesObjectives¢ReviewSASfunctionsusedtocreateSASdatevalues.¢ReviewSASfunctionstoextractinformationfromSASdatevalues.¢UseSASfunctionstodetermineintervalsbetweentwoSASdatevalues.114 5-66Chapter5DataTransformationsCreatingSASDateValuesYoucanusetheMDYorTODAYfunctionstocreateSASdatevalues.TheMDYfunctioncreatesaSASdatevaluefrommonth,day,andyearvalues.NewDateNewDate=MDY(=MDY(monthmonth,,dayday,,yearyear));;TheTODAYfunctionreturnsthecurrentdateasaSASdatevalue.NewDateNewDate=TODAY()=TODAY();;115monthspecifiesanumericexpressionrepresentinganintegerfrom1to12.dayspecifiesanumericexpressionrepresentinganintegerfrom1to31.yearspecifiesanumericexpressionrepresentinganintegerthatidentifiesaspecifictwo-orfour-digityear.!TheDATEfunctionissynonymouswiththeTODAYfunction. 5.4ManipulatingNumericValuesBasedonDates5-67ExtractingInformationYoucanusetheMONTH,DAY,andYEARfunctionstoextractinformationfromSASdatevalues.TheMONTHfunctioncreatesanumericvalue(1-12)thatrepresentsthemonthofaSASdatevalue.NewMonthNewMonth=MONTH(=MONTH(SAS-date-valueSAS-date-value));;116continued... 5-68Chapter5DataTransformationsExtractingInformationTheDAYfunctioncreatesanumericvalue(1-31)thatrepresentsthedayofaSASdatevalue.NewDayNewDay=DAY(=DAY(SAS-date-valueSAS-date-value));;TheYEARfunctioncreatesafour-digitnumericvaluethatrepresentstheyear.NewYearNewYear=YEAR(=YEAR(SAS-date-valueSAS-date-value));;117Othersimilarfunctionsincludethefollowing:QTRreturnsthequarteroftheSASdatevalue(1-4;1representsJanuarythroughMarch,2representsAprilthroughJune,andsoon).WEEKDAYreturnsthedayoftheweekofaSASdatevalue(1-7;1representsSunday,7representsSaturday). 5.4ManipulatingNumericValuesBasedonDates5-69Exercises10.ManipulatingNumericValuesBasedonDatesTheprog2.nodaydatasetcontainsinformationaboutemployees.Useprog2.nodaytocreateanewdatasetnamedemphire.UsetheexistingHiredMonthandHiredYearvariablestocreateanewvariable,Hired,thatstorestheSASdatevalueforeachemployee’sdateofhire.Assumeeachemployeewashiredontheth15dayofthemonth.ThevaluesofHiredshouldbedisplayedusingaDATE9.format.Theemphiredatasetshouldcontainthreevariables:IDandHired.Printthedatasettoverifyyourresults.Listingofprog2.nodayHiredHiredIDMonthYearE0346431994E0652381996E0734611997E09965101999E1346722000ListingofemphireObsIDHiredYears1E0346415MAR1994122E0652315AUG1996103E0734615JAN199794E0996515OCT199975E1346715FEB20006!TheresultsaboveweregeneratedonJanuary9,2007.YourvaluesforYearsmightdiffer. 5-70Chapter5DataTransformations5.5ConvertingVariableTypeObjectives¢Understandautomaticconversionofcharacterdataintonumericdata.¢Explicitlyconvertcharacterdataintonumericdata.¢Understandautomaticconversionofnumericdataintocharacterdata.¢Explicitlyconvertnumericdataintocharacterdata.120DataConversionInmanyapplications,youmightneedtoconvertonedatatypetoanother.¢Youmightneedtoreaddigitsincharacterformintoanumericvalue.¢Youmightneedtowriteanumericvaluetoacharacterstring.121 5.5ConvertingVariableType5-71DataConversionYoucanconvertdatatypes¢implicitlybyallowingtheSASSystemtodoitforyou¢explicitlywiththesefunctions:–INPUTcharacter-to-numericconversion–PUTnumeric-to-characterconversion.122TheINPUTstatementusesaninformattoreadadatavalueandthenoptionallystoresthatvalueinavariable.TheINPUTfunctionreturnsthevalueproducedwhenaSASexpressionisreadusingaspecifiedinformat.ThePUTstatementwritesavaluetoanexternaldestination(eitherthelogoradestinationyouspecify).ThePUTfunctionreturnsavalueusingaspecifiedformat.AutomaticCharacter-to-NumericConversionTheprog2.salary1datasetcontainsacharactervariableGrossPay.Computeatenpercentbonusforeachemployee.WhatwillhappenwhenthecharactervaluesofGrossPayareusedinanarithmeticexpression?123 5-72Chapter5DataTransformationsAutomaticCharacter-to-NumericConversionprog2.salary1IDGrossPay$11$5201-92-249852000482-87-794532000330-40-717249000databonuses;setprog2.salary1;Bonus=.10*GrossPay;run;c05s5d1.sas124AutomaticCharacter-to-NumericConversionPartialLog2databonuses;3setprog2.salary1;4Bonus=.10*GrossPay;5run;NOTE:Charactervalueshavebeenconvertedtonumericvaluesattheplacesgivenby:(Line):(Column).4:14NOTE:ThedatasetWORK.BONUSEShas3observationsand3variables.125 5.5ConvertingVariableType5-73AutomaticCharacter-to-NumericConversionprocprintdata=bonusesnoobs;run;PROCPRINTOutputIDGrossPayBonus201-92-2498520005200482-87-7945320003200330-40-7172490004900126AutomaticCharacter-to-NumericConversionSASautomaticallyconvertsacharactervaluetoanumericvaluewhenthecharactervalueisusedinanumericcontext,suchas¢assignmenttoanumericvariable¢anarithmeticoperation¢logicalcomparisonwithanumericvalue¢afunctionthattakesnumericarguments.127!TheWHEREstatementandWHERE=datasetoptiondonotperformanyautomaticconversionincomparisons. 5-74Chapter5DataTransformationsAutomaticCharacter-to-NumericConversionTheautomaticconversion¢usesthew.informat¢producesanumericmissingvaluefromacharactervaluethatdoesnotconformtostandardnumericnotation(digitswithoptionaldecimalpointand/orleadingsignand/orE-notation).128AutomaticCharacter-to-NumericConversionCharacterNumericvaluevalue5200052000-8.96-8.96Automatic1.243E1conversion12.431,742.64.129 5.5ConvertingVariableType5-75TheINPUTFunctionTheINPUTfunctionisusedprimarilyforconvertingcharactervaluestonumericvalues.NumVarNumVar=INPUT(=INPUT(sourcesource,,informatinformat));;TheINPUTfunctionreturnsthevalueproducedwhensourceisreadwithinformat.130sourcecontainstheSAScharacterexpressiontowhichyouwanttoapplyaspecificinformat.informatistheSASinformatthatyouwanttoapplytothesource.IfyouusetheINPUTfunctiontocreateavariablenotpreviouslydefined,thetypeandlengthofthevariableisdefinedbytheinformat.!NoconversionmessagesarewrittentothelogbytheINPUTfunction. 5-76Chapter5DataTransformationsTheINPUTFunctiondataconversion;CVar1='32000';CVar2='32,000';CVar3='03may2008';CVar4='050308';NVar1=input(CVar1,5.);NVar2=input(CVar2,comma6.);NVar3=input(CVar3,date9.);NVar4=input(CVar4,mmddyy6.);run;131TheINPUTFunctionproccontentsdata=conversion;run;PartialPROCCONTENTSOutput----AlphabeticListofVariablesandAttributes----#VariableTypeLenƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ1CVar1Char52CVar2Char63CVar3Char94CVar4Char65NVar1Num86NVar2Num87NVar3Num88NVar4Num8132 5.5ConvertingVariableType5-77TheINPUTFunctionprocprintdata=conversionnoobs;run;PROCPRINTOutputCVar1CVar2CVar3CVar4NVar13200032,00003may200805030832000NVar2NVar3NVar4320001765517655133ExplicitCharacter-to-NumericConversionThevaluesofthevariableGrossPayintheSASdatasetprog2.salary2containcommas.Attempttouseautomaticconversiontocomputea10percentbonus.prog2.salary2IDGrossPay$11$6201-92-249852,000482-87-794532,000330-40-717249,000134 5-78Chapter5DataTransformationsExplicitCharacter-to-NumericConversiondatabonuses;setprog2.salary2;Bonus=.10*GrossPay;run;procprintdata=bonuses;run;PROCPRINTOutputIDGrossPayBonus201-92-249852,000.482-87-794532,000.330-40-717249,000.135ExplicitCharacter-to-NumericConversiondatabonuses;setprog2.salary2;Bonus=.10*input(GrossPay,comma6.);run;procprintdata=bonuses;run;PROCPRINTOutputIDGrossPayBonus201-92-249852,0005200482-87-794532,0003200330-40-717249,0004900c05s5d2.sas136 5.5ConvertingVariableType5-79DataConversionproccontentsdata=bonuses;run;PartialPROCCONTENTSOutput----AlphabeticListofVariablesandAttributes----#VariableTypeLenƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ3BonusNum82GrossPayChar61IDChar11HowcanyouconvertGrossPaytoanumericvariablewiththesamename?137DataConversionYoucannotconvertdatabyassigningtheconvertedvariablevaluetoavariablewiththesamename.GrossPay=input(GrossPay,comma6.);ThisassignmentstatementThisassignmentstatementdoesdoesnotnotchangechangeGrossPayGrossPayfromacharactervariablefromacharactervariabletoanumericvariable.toanumericvariable.138 5-80Chapter5DataTransformationsDataConversionOntheleftsideoftheassignmentstatement,youwantGrossPaytobenumeric.However,ontherightsideoftheassignmentstatement,GrossPayischaracter.GrossPay=input(GrossPay,comma6.);AvariableischaracterAvariableischaracterornumeric.Aftertheornumeric.Afterthevariabletypeisestablished,variabletypeisestablished,itcannotbechanged.itcannotbechanged.139 5.5ConvertingVariableType5-81DataConversionFirst,usetheRENAME=datasetoptiontorenamethevariableyouwanttoconvert.SAS-data-setSAS-data-set(RENAME=((RENAME=(old-nameold-name==new-namenew-name))))databonuses;setprog2.salary2(rename=(GrossPay=CharGross));additionalSASstatementsrun;140old-namespecifiesthevariableyouwanttorename.new-namespecifiesthenewnameofthevariable.ItmustbeavalidSASname.!Thenewnameofthevariableyouwanttoconvertisarbitrary.Inthisexample,theexistingvariableisrenamedCharGrosstoemphasizethatacharactervariableisbeingconverted.Torenamemorethanonevariablefromthesamedataset,separatethevariablesyouwanttorenamewithaspace.Forexample,torenamenotonlyGrossPay,butalsoID,usethefollowingstatement.setprog2.salary2(rename=(GrossPay=CharGrossID=IDNum)); 5-82Chapter5DataTransformationsDataConversionSecond,usetheINPUTfunctioninanassignmentstatementtocreateanewvariablewhosenameistheoriginalnameofthevariableyourenamedpreviously.databonuses;setprog2.salary2(rename=(GrossPay=CharGross));GrossPay=input(CharGross,comma6.);additionalSASstatementsrun;141DataConversionThird,useaDROP=datasetoptionintheDATAstatementtoexcludetheoriginalvariablefromtheoutputSASdataset.databonuses(drop=CharGross);setprog2.salary2(rename=(GrossPay=CharGross));GrossPay=input(CharGross,comma6.);Bonus=.10*GrossPay;run;c05s5d3.sas142 5.5ConvertingVariableType5-83DataConversion:Compilationdatabonuses(drop=CharGross);setprog2.salary2(rename=(GrossPay=CharGross));GrossPay=input(CharGross,comma6.);Bonus=.10*GrossPay;run;PDVIDCharGross$4$6143...DataConversion:Compilationdatabonuses(drop=CharGross);setprog2.salary2(rename=(GrossPay=CharGross));GrossPay=input(CharGross,comma6.);Bonus=.10*GrossPay;run;PDVIDCharGrossGrossPay$4$6N8144... 5-84Chapter5DataTransformationsDataConversion:Compilationdatabonuses(drop=CharGross);setprog2.salary2(rename=(GrossPay=CharGross));GrossPay=input(CharGross,comma6.);Bonus=.10*GrossPay;run;PDVIDCharGrossGrossPayBonus$4$6N8N8145...DataConversion:Compilationdatabonuses(drop=CharGross);setprog2.salary2(rename=(GrossPay=CharGross));GrossPay=input(CharGross,comma6.);Bonus=.10*GrossPay;run;PDVIDCharGrossGrossPayBonusD$4$6N8N8146 5.5ConvertingVariableType5-85ConvertingCharacterDatestoSASDatesprog2.bornNameDate$12$7Ruth,G.H.13apr72Delgado,Ed25aug68Overby,Phil08jun71databirth(drop=Date);setprog2.born;Birthday=input(Date,date7.);run;c05s5d4.sas147ConvertingCharacterDatestoSASDatesprocprintdata=birthnoobs;run;PROCPRINTOutputNameBirthdayRuth,G.H.4486Delgado,Ed3159Overby,Phil4176148 5-86Chapter5DataTransformationsAutomaticNumeric-to-CharacterConversionTheprog2.phonesdatasetcontainsanumericvariableCode(areacode)andacharactervariableTelephone(telephonenumber).Createacharactervariablethatcontainstheareacodeinparenthesesfollowedbythetelephonenumber.149AutomaticNumeric-to-CharacterConversionprog2.phonesCodeTelephoneN8$8303393-0956919770-8292301449-5239dataphonenumbers;setprog2.phones;Phone='('!!Code!!')'!!Telephone;run;c05s5d5.sas150 5.5ConvertingVariableType5-87AutomaticNumeric-to-CharacterConversionPartialLog13dataphonenumbers;14setprog2.phones;15Phone='('!!Code!!')'!!Telephone;16run;NOTE:Numericvalueshavebeenconvertedtocharactervaluesattheplacesgivenby:(Line):(Column).15:17NOTE:ThedatasetWORK.PHONENUMBERShas3observationsand3variables.151AutomaticNumeric-to-CharacterConversionprocprintdata=phonenumbersnoobs;run;PROCPRINTOutputCodeTelephonePhone303393-0956(303)393-0956919770-8292(919)770-8292301449-5239(301)449-5239152 5-88Chapter5DataTransformationsAutomaticNumeric-to-CharacterConversionSASautomaticallyconvertsanumericvaluetoacharactervaluewhenthenumericvalueisusedinacharactercontext,suchas¢assignmenttoacharactervariable¢aconcatenationoperation¢afunctionthatacceptscharacterarguments.153!TheWHEREstatementandWHERE=datasetoptiondonotperformanyautomaticconversionincomparisons.AutomaticNumeric-to-CharacterConversionTheautomaticconversion¢usestheBEST12.format¢right-alignstheresultingcharactervalue.NumericCharactervalue:value:8bytes12bytes303Automaticconversion3039leadingblanks154 5.5ConvertingVariableType5-89AutomaticNumeric-to-CharacterConversiondataphonenumbers;setprog2.phones;Phone='('!!Code!!')'!!Telephone;run;Phone$23(303)393-09569leadingblanks155 5-90Chapter5DataTransformationsThePUTFunctionThePUTfunctionwritesvalueswithaspecificformat.CharVarCharVar=PUT(=PUT(sourcesource,,formatformat));;ThePUTfunctionreturnsthevalueproducedwhensourceiswrittenwithformat.156sourceidentifiestheSASvariableorconstantwhosevalueyouwanttoreformat.Thisargumentcanbecharacterornumeric.formatcontainstheSASformatthatyouwantappliedtothevariableorconstantthatisspecifiedinthesource.Itmustagreewiththesourceintype.ThePUTfunctionalwaysreturnsacharacterstring.Numericformatsright-aligntheresults.Characterformatsleft-aligntheresults.IfyouusethePUTfunctiontocreateavariablenotpreviouslydefined,itcreatesacharactervariablewithalengthequaltotheformatwidth.!NoconversionmessagesarewrittentothelogbythePUTfunction. 5.5ConvertingVariableType5-91ThePUTFunctiondataconversion;NVar1=614;NVar2=55000;NVar3=366;CVar1=put(NVar1,3.);CVar2=put(NVar2,dollar7.);CVar3=put(NVar3,date9.);run;157ThePUTFunctionproccontentsdata=conversionvarnum;run;TheVARNUMoptioninthePROCCONTENTSstatementprintsalistofthevariablesbytheirlogicalpositioninthedataset.PartialPROCCONTENTSOutput-----VariablesOrderedbyPosition-----#VariableTypeLenƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ1NVar1Num82NVar2Num83NVar3Num84CVar1Char35CVar2Char76CVar3Char9158 5-92Chapter5DataTransformationsThePUTFunctionprocprintdata=conversionnoobs;run;PROCPRINTOutputNVar1NVar2NVar3CVar1CVar2CVar361455000366614$55,00001JAN1961159ExplicitNumeric-to-CharacterConversiondataphonenumbers;setprog2.phones;Phone='('!!put(Code,3.)!!')'!!Telephone;run;PartialLog20dataphonenumbers;21setprog2.phone;22Phone='('!!put(Code,3.)!!')'!!Telephone;23run;NOTE:ThedatasetWORK.PHONENUMBERShas3observationsand3variables.c05s5d6.sas160 5.5ConvertingVariableType5-93AutomaticNumeric-to-CharacterConversionprocprintdata=phonenumbersnoobs;run;PROCPRINTOutputCodeTelephonePhone303393-0956(303)393-0956919770-8292(919)770-8292301449-5239(301)449-5239161 5-94Chapter5DataTransformationsExercises11.ConvertingVariableTypeThedatasetprog2.studentscontainsinformationaboutstudents.PartialPROCCONTENTSOutputofprog2.students-----AlphabeticListofVariablesandAttributes-----#VariableTypeLenƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ3DOBChar92NumberNum81SSNChar11PartialListingofprog2.studentsSSNNumberDOB012-40-4928546788705DEC1968012-83-3816688832103MAY1965341-44-0781941812323NOV1972423-01-7721783919128JUN1967448-23-8111942812230NOV1960Createanewdatasetnamedstudentsfromprog2.students.CreateanewcharactervariableTelephonethathasthispattern:XXX-XXXX,whereXXXXXXXisthevalueofNumber.Printthestudentsdatasetandlistallthevariablestoverifythedataconversion.RecallthepreviousprogramandalterittocreateanewnumericvariableBirthdayfromtheDOBvariable.BirthdayshouldcontainSASdatevaluesandhaveaformatofMMDDYY10.Printthestudentsdatasetandlistallthevariablestoverifythedataconversion.Whenyouareconfidentthatbothvariableswereconvertedcorrectly,useaDROP=orKEEP=datasetoptiontoensurethattheonlyvariablesinthestudentsdatasetareSSN,Telephone,andBirthday.Printyourdatasettoverifyyourresults.PartialListingofstudentsObsSSNTelephoneBirthday1012-40-4928546-788712/05/19682012-83-3816688-832105/03/19653341-44-0781941-812311/23/19724423-01-7721783-919106/28/19675448-23-8111942-812211/30/1960 5.6SolutionstoExercises5-955.6SolutionstoExercises1.ManipulatingCharacterValuesdataseparate(drop=FMnames);lengthFMnamesFirst$30MI$2Last$30;setprog2.people;FMnames=left(scan(Name,2,','));First=scan(FMnames,1,'');MI=left(scan(FMnames,2,''));Last=scan(Name,1,',');run;procprintdata=separate;varNameCityStateFirstMILast;run;2.CombiningCharacterValuesdataflname(keep=NewNameCityState);lengthFMnamesFirstMILast$30;setprog2.people;FMnames=left(scan(Name,2,','));First=scan(FMnames,1,'');MI=left(scan(FMnames,2,''));Last=left(scan(Name,1,','));/*Puttogetherjustthefirstnameandthelastname.*/NewName=trim(First)!!''!!Last;run;procprintdata=flname;varNewNameCityState;run; 5-96Chapter5DataTransformations®Alternatesolution(SAS9):dataflname(keep=NewNameCityState);lengthFMnamesFirstMILast$30;setprog2.people;FMnames=left(scan(Name,2,','));First=scan(FMnames,1,'');MI=left(scan(FMnames,2,''));Last=left(scan(Name,1,','));NewName=catx('',First,Last);run;procprintdata=flname;varNewNameCityState;run;3.PerformingAdditionalCharacterManipulations(Optional)datainit(drop=FirstMILastFMNames);lengthInitials$3LastFMNamesFirstMI$30;setprog2.people;FMNames=scan(Name,2,',');First=scan(FMNames,1,'');MI=scan(FMNames,2,'');Last=scan(Name,1,',');/*Puttogetherjustthefirstletters*/Initials=substr(First,1,1)!!substr(MI,1,1)!!substr(Last,1,1);run;procprintdata=init;varNameCityStateinitials;run; 5.6SolutionstoExercises5-97TheTRIMNfunctionreturnsanullstring(zeroblanks)forablankstring.TheTRIMfunctionreturnsasingleblank.®Alternatesolution(SAS9):datainit(drop=FirstMILastFMNames);lengthInitials$3LastFirstMI$1FMNames$30;setprog2.people;FMNames=scan(Name,2,',');/*Byassigningentirenamesinto1-bytecharactervariables,everythingistruncatedexceptthefirstletter.*/First=left(FMNames);MI=scan(FMNames,2,'');Last=Name;/*TheCATfunctionconcatenateswithouttrimmingorinsertingseparators.*/Initials=cat(First,MI,Last);run;procprintdata=init;varNameCityStateinitials;run;4.SearchingforaCharacterValuedataprairie;setprog2.people;/*SecondargumenttoINDEXfunctionmustincludealeadingblankto®avoidextraneousresults.TheSAS9FINDfunctioncanalsobeusedhere.*/ifindex(CityState,'IL')>0;run;procprintdata=prairie;run; 5-98Chapter5DataTransformations5.PerformingAdditionalCharacterManipulationsdatamixedprairie(drop=FirstMILastFMNames);lengthLastFMNamesFirstMI$30;setprairie;Last=scan(Name,1,',');FMnames=scan(Name,2,',');First=scan(FMnames,1,'');MI=scan(FMnames,2,'');substr(First,2)=lowcase(substr(First,2));substr(Last,2)=lowcase(substr(Last,2));Name=trim(Last)!!','!!trim(First)!!''!!MI;run;procprintdata=mixedprairie;run;®Alternatesolution(SAS9):datamixedprairie;setprairie;Name=propcase(Name);run;procprintdata=mixedprairie;run;6.UsingAdditionalCharacterFunctionsdatastatelong(keep=NameStateName);lengthStateNameState$20;setprog2.people;/*SecondwordofCITYSTATEisextracted.ResultingsecondwordofCITYSTATEisleft-alignedtoeliminateleadingblank.Oncetheleadingblankisremoved,STNAMELcanbeusedtodeterminestatename.*/State=left(scan(CityState,2,','));StateName=stnamel(State);run;procprintdata=statelong;varNameStateName;run; 5.6SolutionstoExercises5-997.PerformingAdditionalCharacterManipulations(Optional)datamixedall(keep=NameCityState);lengthFMNamesMNameFNameLName$30;setprog2.people;/*TheentirevalueofNameistransformedintolowercaselettersbecause,inyourfinalresults,mostofthelettersinthevalueofNamearelowercase.*/Name=lowcase(Name);/*Extractthelastname,andplaceitsfirstcharacterbackintouppercase.*/LName=scan(Name,1,',');substr(LName,1,1)=upcase(substr(LName,1,1));/*UsetheINDEXfunctiontosearchforablankwithinthevalueofLName.Ifablankisfound,uppercasethecharacteronepositiontoitsright.Thisisthefirstcharacterofthesecondwordofamultiple-wordlastname.*/BlankPos=index(LName,'');ifBlankPosgt0thensubstr(LName,BlankPos+1,1)=upcase(substr(LName,BlankPos+1,1));/*Extractthefirstandmiddlenames,andplacetheirfirstcharactersbackintouppercase.*/FMNames=left(scan(Name,2,','));FName=scan(FMNames,1,'');MName=scan(FMNames,2,'');substr(FName,1,1)=upcase(substr(FName,1,1));substr(MName,1,1)=upcase(substr(MName,1,1));/*UsetheINDEXfunctiontosearchforahyphenwithinthevalueofLName.Ifahyphenisfound,uppercasethecharacteronepositiontoitsright.Thisisthefirstcharacterofthesecondwordofamultiple-wordlastname.*/DashPos=index(FName,'-');ifDashPosgt0thensubstr(FName,DashPos+1,1)=upcase(substr(FName,DashPos+1,1));Name=trim(LName)!!','!!trim(FName)!!''!!MName;run;procprintdata=mixedall;run; 5-100Chapter5DataTransformations®Alternatesolution(SAS9):datamixedall;setprog2.people;Name=propcase(Name);run;procprintdata=mixedall;run;8.ManipulatingNumericValuesdatafinal;setprog2.grade;Overall=round(mean(Test1,Test2,Test3,Final,Final));run;/*TheassignmentstatementabovecouldbereplacedwithOverall=round(mean(ofTest1-Test3,Final,Final));*/procprintdata=final;run;9.PerformingAdditionalNumericManipulations(Optional)datafinal(drop=OverallTotal);setprog2.grade;OverallTotal=sum(Test1,Test2,Test3,Final,Final)-min(Test1,Test2,Test3);Overall=round(OverallTotal/4);run;/*ThefirstassignmentstatementabovecouldbereplacedwithOverallTotal=sum(ofTest1-Test3,Final,Final)-min(ofTest1-Test3);*/procprintdata=final;run; 5.6SolutionstoExercises5-10110.ManipulatingNumericValuesBasedonDatesdataemphire(keep=IDHired);setprog2.noday;Hired=mdy(HiredMonth,15,HiredYear);/*TheFLOORfunctioncouldbeusedinthefollowingassignmentstatement:*/formatHireddate9.;run;procprintdata=emphire;run;11.ConvertingVariableTypedatastudents(drop=NumberDOB);setprog2.students;/*ThePUTfunctionisusedtoconvertNUMBERfromnumerictocharacter,andthentheresultingcharactervalueismanipulatedwiththeSUBSTRfunctiontoextractthefirstthreecharacters,andthelastfourcharacters.*/Telephone=substr(put(Number,7.),1,3)!!'-'!!substr(put(Number,7.),4);/*TheINPUTfunctionisusedtoconvertDOBfromcharactertonumeric.BecausethecharactervaluesareintheformddMMMyyyy,theDATE9.formatisusedintheconversion.*/Birthday=input(DOB,date9.);formatBirthdaymmddyy10.;run;procprintdata=students;run; 5-102Chapter5DataTransformations Chapter6DebuggingTechniques(Self-Study)6.1UsingthePUTStatement...............................................................................................6-36.2UsingtheDEBUGOption.............................................................................................6-15 6-2Chapter6DebuggingTechniques(Self-Study) 6.1UsingthePUTStatement6-36.1UsingthePUTStatementObjectives¢UsethePUTstatementintheDATAsteptohelpidentifylogicproblems.3ScenarioYoutookanewpositioninthe??company.Yourpredecessorwrotesomecodethatisnot?working.Identifywhattheprogramcodeiscurrentlydoinganddeterminetheproblem.4 6-4Chapter6DebuggingTechniques(Self-Study)InputDataCityCountryStateAuckland,NewZealandKansasCity,USAMissouriCanberra,AustraliaAustralianCapitalAthens(Athinai),GreeceAmsterdam,NetherlandsAnchorage,USAAlaskaBirmingham,USAAlabamaBangkok,ThailandNashville,USATennesseeBoston,USAMassachusetts5ExpectedResultsTrueLocationAuckland,NewZealandKansasCity,MissouriCanberra,AustraliaAthens(Athinai),GreeceAmsterdam,NetherlandsAnchorage,AlaskaBirmingham,AlabamaBangkok,ThailandNashville,TennesseeBoston,Massachusetts6 6.1UsingthePUTStatement6-5CurrentProgramdatawork.agents2;setprog2.agents;lengthCountry$20;Country=scan(CityCountry,2,',');ifCountry='USA'thenTrueLocation=scan(CityCountry,1,',')!!','!!State;else/*notUSA*/TrueLocation=CityCountry;run;7CurrentResultsTrueLocationAuckland,NewZealandKansasCity,USACanberra,AustraliaAthens(Athinai),GreeceAmsterdam,NetherlandsAnchorage,USABirmingham,USABangkok,ThailandNashville,USABoston,USA8 6-6Chapter6DebuggingTechniques(Self-Study)SyntaxErrorsVersusLogicErrors¢AsyntaxerroroccurswhenprogramstatementsdonotconformtotherulesoftheSASlanguage.AnerrormessageisproducedbytheSASSystemandwrittentothelog.¢Alogicerroroccurswhentheprogramstatementsfollowtherules,buttheresultsarenotcorrect.Thissectionfocusesonlogicerrors.9Becauselogicerrorsdonotproducenotesinthelog,theyareoftendifficulttodetectandcorrect.ThePUTstatementandtheDATAstepdebugger(discussedinthenextsection)aretwomethodsfordetectinglogicerrors.ThePUTStatementIfyoudonotspecifyaFILEstatement,thePUTstatementwritesinformationtothelog.Thisisusefultodetermine¢whichpieceofcodeisexecuting¢whichpieceofcodeisnotexecuting¢thecurrentvalueofaparticularvariable¢thecurrentvaluesofallvariables.10 6.1UsingthePUTStatement6-7GeneralFormsofthePUTStatementPUTPUT'text'text';';writestheliteraltextstring.Example:put'Iamhere.';writesIamhere.tothelog.11GeneralFormsofthePUTStatementPUTPUTvariable-namevariable-name==;;writesthenameofthevariablefollowedbyanequalsignandthevalue.Example:IfthevalueofthevariableVaris5,thestatementputVar=;writesVar=5tothelog.12 6-8Chapter6DebuggingTechniques(Self-Study)GeneralFormsofthePUTStatementPUTPUTvariable-nameformat-namevariable-nameformat-name..;;writesthevariablevaluewiththeindicatedformat.Example:IfthevalueofthevariableChVarisTHISwithaleadingspace,thestatementputChVar$quote20.;writes"THIS"tothelog.13!Theformat$QUOTEw.writesacharactervaluewithquotesarounditandpreservesanyleadingspaces.GeneralFormsofthePUTStatementPUTPUT_ALL__ALL_;;writesthenameofeachvariableinthePDVfollowedbyanequalsignandthevalueofthevariable.14!ThePUTstatementcanbeusedinSASinboththebatchandinteractivemodes. 6.1UsingthePUTStatement6-9ThePUTLOGStatementThePUTLOGstatementissimilartothePUTstatement,exceptthatitwritesonlytothelog.ItisunaffectedbytheFILEstatement.PUTLOGPUTLOGmessagemessage;;wheremessagecanincludecharacterliterals(enclosedinquotationmarks),variablenames,formats,andpointercontrols.!PUTLOGisaSAS®9statement.15TheadvantageofthePUTLOGstatementisthatitcanbeinsertedinaDATAstepwhichhasPUTandFILEstatementswritingtoanon-logdestination(suchasadiskfile)withoutaffectingthatlogic. 6-10Chapter6DebuggingTechniques(Self-Study)DeterminingLogicErrorsc06s1d1.sas,c06s1d2.sasThisdemonstrationshowshowtodetectandcorrectlogicerrorsusingthePUTstatement.datawork.agents2;setprog2.agents;lengthCountry$20TrueLocation$40;Country=scan(CityCountry,2,',');ifcountry='USA'thenTrueLocation=scan(CityCountry,1,',')!!','!!State;else/*notUSA*/TrueLocation=CityCountry;run;procprintdata=work.agents2noobs;varTrueLocationCityCountryState;title'CurrentOutputfromProgram';run;PROCPRINTOutputCurrentOutputfromProgramCityCountryTrueLocationStateAuckland,NewZealandAuckland,NewZealandKansasCity,USAKansasCity,USAMissouriCanberra,AustraliaCanberra,AustraliaAustralianCapitalAthens(Athinai),GreeceAthens(Athinai),GreeceAmsterdam,NetherlandsAmsterdam,NetherlandsAnchorage,USAAnchorage,USAAlaskaBirmingham,USABirmingham,USAAlabamaBangkok,ThailandBangkok,ThailandNashville,USANashville,USATennesseeBoston,USABoston,USAMassachusetts 6.1UsingthePUTStatement6-11BringthecodeintotheEditorwindow.1.Determinewhatcodeisexecuting.ConverttheIF-THENstatementthatcreatesTrueLocationforUSAbranchesintoaDOgroup,®andinsertaPUT(orPUTLOG–SAS9)statementtodeterminewhetherthecodeisexecuting.datawork.agents2;setprog2.agents;lengthCountry$20TrueLocation$40;Country=scan(CityCountry,2,',');ifCountry='USA'thendo;TrueLocation=scan(CityCountry,1,',')!!','!!State;put'CountryisUSA';end;else/*notUSA*/TrueLocation=CityCountry;run;Submitthecode.ThetextstringinthePUTstatementdoesnotappearinthelog.2.DeterminethevalueofCountrybeforetheIF-THENstatement.InsertaPUTstatementbetweentheassignmentstatementforCountryandtheIF-THENstatementthatcreatesTrueLocationforUSAbranches.datawork.agents2;setprog2.agents;lengthCountry$20TrueLocation$40;Country=scan(CityCountry,2,',');putCountry=;ifCountry='USA'thendo;TrueLocation=scan(CityCountry,1,',')!!','!!State;put'CountryisUSA';end;else/*notUSA*/TrueLocation=CityCountry;run;Submitthecode.ThevaluesofCountryseemtobecreatedappropriately.PartialLogCountry=NewZealandCountry=USACountry=AustraliaCountry=GreeceCountry=NetherlandsCountry=USA 6-12Chapter6DebuggingTechniques(Self-Study)3.Usethe$QUOTEw.formattocheckforleadingblanks.Bydefault,charactervaluesarewrittenwiththestandardcharacterformat$w.,wherewisthelengthofthecharactervariable.Thestandardcharacterformatleft-justifiesthevalueandremovesleadingblanks.TocheckforleadingblanksinthevalueforCountry,changethePUTstatementasshownbelow:datawork.agents2;setprog2.agents;lengthCountry$20TrueLocation$40;Country=scan(CityCountry,2,',');putCountry$quote20.;ifCountry='USA'thendo;TrueLocation=scan(CityCountry,1,',')!!','!!State;put'CountryisUSA';end;else/*notUSA*/TrueLocation=CityCountry;run;Submitthecodeandcheckthelog.Noticethateachvalueshowsoneleadingblank.PartialLog"NewZealand""USA""Australia""Greece""Netherlands""USA"4.UsetheLEFTfunctiontoremoveleadingblanksfromthevaluesofCountry.datawork.agents2;setprog2.agents;lengthCountry$20TrueLocation$40;Country=left(scan(CityCountry,2,','));putCountry$quote20.;ifCountry='USA'thendo;TrueLocation=scan(CityCountry,1,',')!!','!!State;put'CountryisUSA';end;else/*notUSA*/TrueLocation=CityCountry;run;Submitthecodeandcheckthelog.ThePUTstatementintheDOgroupwritestothelogattheappropriatetime. 6.1UsingthePUTStatement6-13PartialLog"NewZealand""USA"CountryisUSA"Australia""Greece""Netherlands""USA"CountryisUSAprocprintdata=work.agents2noobs;varTrueLocationCityCountryState;title'OutputwithLeadingSpacesRemoved';run;PROCPRINTOutputOutputwithLeadingSpacesRemovedTrueLocationCityCountryStateAuckland,NewZealandAuckland,NewZealandKansasCity,MissouriKansasCity,USAMissouriCanberra,AustraliaCanberra,AustraliaAustralianCapitalAthens(Athinai),GreeceAthens(Athinai),GreeceAmsterdam,NetherlandsAmsterdam,NetherlandsAnchorage,AlaskaAnchorage,USAAlaskaBirmingham,AlabamaBirmingham,USAAlabamaBangkok,ThailandBangkok,ThailandNashville,TennesseeNashville,USATennesseeBoston,MassachusettsBoston,USAMassachusetts 6-14Chapter6DebuggingTechniques(Self-Study)5.RemovethePUTstatementsandtheDOgroupfromtheDATAstep.datawork.agents2(drop=Country);setprog2.agents;lengthCountry$20TrueLocation$40;Country=left(scan(CityCountry,2,','));ifCountry='USA'thenTrueLocation=scan(CityCountry,1,',')!!','!!State;else/*notUSA*/TrueLocation=CityCountry;run;procprintdata=work.agents2noobs;varTrueLocationCityCountryState;title'CorrectedOutput';run;Submitthecodeandcheckthelogandoutput.PROCPRINTOutputCorrectedOutputTrueLocationCityCountryStateAuckland,NewZealandAuckland,NewZealandKansasCity,MissouriKansasCity,USAMissouriCanberra,AustraliaCanberra,AustraliaAustralianCapitalAthens(Athinai),GreeceAthens(Athinai),GreeceAmsterdam,NetherlandsAmsterdam,NetherlandsAnchorage,AlaskaAnchorage,USAAlaskaBirmingham,AlabamaBirmingham,USAAlabamaBangkok,ThailandBangkok,ThailandNashville,TennesseeNashville,USATennesseeBoston,MassachusettsBoston,USAMassachusetts 6.2UsingtheDEBUGOption6-156.2UsingtheDEBUGOptionObjectives¢UsetheDEBUGoptionintheDATAstatementtohelpidentifylogicproblems.18ScenarioYoutookanewpositioninthecompany.Yourpredecessor??wrotesomecodethatisnot?working.Identifywhattheprogramcodeiscurrentlydoinganddeterminetheproblem.19 6-16Chapter6DebuggingTechniques(Self-Study)InputDataCityCountryStateAuckland,NewZealandKansasCity,USAMissouriCanberra,AustraliaAustralianCapitalAthens(Athinai),GreeceAmsterdam,NetherlandsAnchorage,USAAlaskaBirmingham,USAAlabamaBangkok,ThailandNashville,USATennesseeBoston,USAMassachusetts20ExpectedResultsTrueLocationAuckland,NewZealandKansasCity,MissouriCanberra,AustraliaAthens(Athinai),GreeceAmsterdam,NetherlandsAnchorage,AlaskaBirmingham,AlabamaBangkok,ThailandNashville,TennesseeBoston,Massachusetts21 6.2UsingtheDEBUGOption6-17CurrentProgramdatawork.agents2;setprog2.agents;lengthCountry$20;Country=scan(CityCountry,2,',');ifCountry='USA'thenTrueLocation=scan(CityCountry,1,',')!!','!!State;else/*notUSA*/TrueLocation=CityCountry;run;22CurrentResultsTrueLocationAuckland,NewZealandKansasCity,USACanberra,AustraliaAthens(Athinai),GreeceAmsterdam,NetherlandsAnchorage,USABirmingham,USABangkok,ThailandNashville,USABoston,USA23 6-18Chapter6DebuggingTechniques(Self-Study)TheDEBUGOptionTheDEBUGoptionisaninteractiveinterfacetotheDATAstepduringDATAstepexecution.Thisoptionisusefulfordeterminingthefollowing:¢thecodethatisexecuting¢thecodethatisnotexecuting¢thecurrentvalueofaparticularvariable¢whenthevalueofavariablechanges24!TheDEBUGoptioncanbeusedonlyintheSASSystem’sinteractivemode.TheDEBUGOptionGeneralformoftheDEBUGoption:DATADATAdata-set-namedata-set-name/DEBUG/DEBUG;;25 6.2UsingtheDEBUGOption6-19DEBUGCommandsCommoncommandsusedwiththeDEBUGoption:CommandAbbreviationActionSTEPENTERkeyStepsthroughaprogramonestatementatatime.EXAMINEEvariable(s)Displaysthevalueofthevariable.WATCHWvariable(s)Suspendsexecutionwhenthevalueofthevariablechanges.LISTWATCHLWListsvariablesthatarewatched.QUITQHaltsexecutionoftheDATAstep.26TheWandEcommandsprecedethenameofthevariable,forexample:WCountryToviewthevaluesofallvariables,usethecommande_all_!Youcanalsoselectthesecommandsfromthedrop-downmenuifitisturnedon. 6-20Chapter6DebuggingTechniques(Self-Study)DeterminingLogicErrorsc06s2d1.sasUsetheDEBUGoptiontodetectthelogicerrorinthefollowingprogram:datawork.agents2;setprog2.agents;lengthCountry$20TrueLocation$40;Country=scan(CityCountry,2,',');ifCountry='USA'thenTrueLocation=scan(CityCountry,1,',')!!','!!State;else/*notUSA*/TrueLocation=CityCountry;run;procprintdata=work.agents2noobs;varTrueLocationState;title'LocationsofTicketAgents';run;PROCPRINTOutputLocationsofTicketAgentsTrueLocationCityCountryStateAuckland,NewZealandAuckland,NewZealandKansasCity,USAKansasCity,USAMissouriCanberra,AustraliaCanberra,AustraliaAustralianCapitalAthens(Athinai),GreeceAthens(Athinai),GreeceAmsterdam,NetherlandsAmsterdam,NetherlandsAnchorage,USAAnchorage,USAAlaskaBirmingham,USABirmingham,USAAlabamaBangkok,ThailandBangkok,ThailandNashville,USANashville,USATennesseeBoston,USABoston,USAMassachusettsThecorrectoutputisshownbelow:LocationsofTicketAgentsTrueLocationCityCountryStateAuckland,NewZealandAuckland,NewZealandKansasCity,MissouriKansasCity,USAMissouriCanberra,AustraliaCanberra,AustraliaAustralianCapitalAthens(Athinai),GreeceAthens(Athinai),GreeceAmsterdam,NetherlandsAmsterdam,NetherlandsAnchorage,AlaskaAnchorage,USAAlaskaBirmingham,AlabamaBirmingham,USAAlabamaBangkok,ThailandBangkok,ThailandNashville,TennesseeNashville,USATennesseeBoston,MassachusettsBoston,USAMassachusetts 6.2UsingtheDEBUGOption6-211.AddtheDEBUGoptiontotheendoftheDATAstatement.datawork.agents2/debug;setprog2.agents;lengthCountry$20TrueLocation$40;Country=scan(CityCountry,2,',');ifCountry='USA'thenTrueLocation=scan(CityCountry,1,',')!!','!!State;else/*notUSA*/TrueLocation=CityCountry;run;2.SubmittheDATAstep.!Thedebuggersourcehighlightsthenextstatementtobeexecuted.3.PresstheENTERkeytoexecutetheSETstatement. 6-22Chapter6DebuggingTechniques(Self-Study)4.UsetheExaminecommandtoexaminethevalueofCityCountry:ecitycountry5.PressENTERtoexecutetheassignmentstatementforCountry.6.UsetheExaminecommandtoexaminethevalueofCountry:ecountry7.PressENTERtochecktheconditionalstatement.8.PressENTERtoexecutetheELSEstatement.9.UsetheExaminecommandtoexaminethevalueofTrueLocation:etruelocation 6.2UsingtheDEBUGOption6-2310.UsetheWatchcommandtomonitorthevaluesofTrueLocation,Country,andCityCountry:wtruelocationcountrycitycountry11.PressENTERuntilyouexecutetheSETstatementandtheassignmentstatementforCountry.ThevalueofCountryisnowUSA.12.PressENTERtochecktheIF-THENstatements.13.Noticethechangesinthevaluesofthewatchedvariablesfromstep10. 6-24Chapter6DebuggingTechniques(Self-Study)14.UsetheExaminecommandtocheckthevalueofCountryforleadingspaces:ecountry$quote20.15.PressENTERuntilSASreachesthebottomoftheDATAstep.16.UsetheQuitcommandtohalttheDATAstep. 6.2UsingtheDEBUGOption6-2517.RemovetheDEBUGoptionfromtheDATAstepandusetheLEFTfunctiontoremovetheleadingspace.datawork.agents2(drop=CityCountryCountry);setprog2.agents;lengthCountry$20TrueLocation$40;Country=left(scan(CityCountry,2,','));ifCountry='USA'thenTrueLocation=scan(CityCountry,1,',')!!','!!State;else/*notUSA*/TrueLocation=CityCountry;run;procprintdata=work.agents2noobs;varTrueLocationCityCountryState;title'LocationsofTicketAgents';run;PROCPRINTOutputLocationsofTicketAgentsTrueLocationCityCountryStateAuckland,NewZealandAuckland,NewZealandKansasCity,MissouriKansasCity,USAMissouriCanberra,AustraliaCanberra,AustraliaAustralianCapitalAthens(Athinai),GreeceAthens(Athinai),GreeceAmsterdam,NetherlandsAmsterdam,NetherlandsAnchorage,AlaskaAnchorage,USAAlaskaBirmingham,AlabamaBirmingham,USAAlabamaBangkok,ThailandBangkok,ThailandNashville,TennesseeNashville,USATennesseeBoston,MassachusettsBoston,USAMassachusetts 6-26Chapter6DebuggingTechniques(Self-Study) Chapter7ProcessingDataIteratively7.1DOLoopProcessing......................................................................................................7-37.2SASArrayProcessing..................................................................................................7-377.3UsingSASArrays.........................................................................................................7-527.4SolutionstoExercises.................................................................................................7-75 7-2Chapter7ProcessingDataIteratively 7.1DOLoopProcessing7-37.1DOLoopProcessingObjectives¢UnderstanditerativeDOloops.¢UseDOloopstogeneratedata.¢UseDOloopstoeliminateredundantcode.¢UseDOloopprocessingtoconditionallyexecutecode.3DOLoopProcessingStatementswithinaDOloopexecuteforaspecificnumberofiterationsoruntilaspecificconditionstopstheloop.DATAstatementDOstatementiteratedSASstatementsENDstatementRUNstatement4 7-4Chapter7ProcessingDataIterativelyDOLoopProcessingYoucanuseDOloopsto¢performrepetitivecalculations¢generatedata¢eliminateredundantcode¢executeSAScodeconditionally.5RepetitiveCodingComparetheinterestforyearlyversusquarterlycompoundingona$50,000investmentmadeforoneyearat7.5percentinterest.Howmuchmoneywillapersonaccrueineachsituation?6 7.1DOLoopProcessing7-5RepetitiveCodingdatacompound;Amount=50000;Rate=.075;Yearly=Amount*Rate;Quarterly+((Quarterly+Amount)*Rate/4);Quarterly+((Quarterly+Amount)*Rate/4);Quarterly+((Quarterly+Amount)*Rate/4);Quarterly+((Quarterly+Amount)*Rate/4);run;7RepetitiveCodingprocprintdata=compoundnoobs;run;PROCPRINTOutputAmountRateYearlyQuarterly500000.07537503856.79Whatifyouwantedtodeterminethequarterlycompoundedinterestafteraperiodof20years(80quarters)?8 7-6Chapter7ProcessingDataIterativelyDOLoopProcessingdatacompound(drop=i);Amount=50000;Rate=.075;Yearly=Amount*Rate;doi=1to4;Quarterly+((Quarterly+Amount)*Rate/4);end;run;9 7.1DOLoopProcessing7-7TheIterativeDOStatementTheiterativeDOstatementexecutesstatementsbetweenDOandENDstatementsrepetitively,basedonthevalueofanindexvariable.DODOindex-variableindex-variable==specification-1specification-1<,…<,…specification-nspecification-n>;>;iteratedSASstatementsiteratedSASstatementsEND;END;specification-1…specification-ncanrepresentarangeofvaluesoralistofspecificvalues.10index-variablenamesavariablewhosevaluegovernsexecutionoftheDOloop.Theindex-variableargumentisrequired.specificationdenotesanexpressionoraseriesofexpressions.TheiterativeDOstatementrequiresatleastonespecificationargument.!Theindexvariable,unlessdropped,isincludedinthedatasetthatisbeingcreated.AvoidchangingthevalueoftheindexvariablewithintheDOloop.IfyoumodifythevalueoftheindexvariablewithintheDOloop,youcouldcauseinfinitelooping. 7-8Chapter7ProcessingDataIterativelyTheIterativeDOStatementDODOindex-variableindex-variable==startstartTOTOstopstop;>;Thevaluesofstart,stop,andincrement¢mustbenumbersorexpressionsthatyieldnumbers¢areestablishedbeforeexecutingtheloop.AnychangestothevaluesofstoporincrementmadewithintheDOloopdonotaffectthenumberofiterations.11startspecifiestheinitialvalueoftheindexvariable.stopspecifiestheendingvalueoftheindexvariable.incrementoptionallyspecifiesapositiveornegativenumbertocontroltheincrementingofindex-variable.Ifincrementisnotspecified,theindexvariableisincreasedby1.!Whenincrementispositive,startmustbethelowerboundandstop,ifpresent,mustbetheupperboundfortheloop.Ifincrementisnegative,startmustbetheupperboundandstop,ifpresent,mustbethelowerboundfortheloop. 7.1DOLoopProcessing7-9TheIterativeDOStatementWhatarethevaluesofeachofthefourindexvariables?doi=1to12;Outofrange12345678910111213doj=2to10by2;Outofrange24681012dok=14to2by–2;Outofrange14121086420dom=3.6to3.8by.05;Outofrange3.603.653.703.753.803.8516TheIterativeDOStatementDODOindex-variableindex-variable==item-1…item-n>;;item-1throughitem-ncanbeeitherallnumericorallcharacterconstants,ortheycanbevariables.TheDOloopisexecutedonceforeachvalueinthelist.17!Enclosecharacterconstantsinquotationmarks. 7-10Chapter7ProcessingDataIterativelyTheIterativeDOStatementHowmanytimeswilleachDOloopexecute?doMonth='JAN','FEB','MAR';Threetimes.doFib=1,2,3,5,8,13,21;Seventimes.doi=Var1,Var2,Var3;Threetimes.doj=BeginDatetoToday()by7;Unknown.ThenumberofiterationsdependsonthevaluesofBeginDateandToday().dok=Test1-Test50;Onetime.AsinglevalueofkisdeterminedbysubtractingTest50fromTest1.23...InitializePDV.DOLoopLogicExecute“read”EOFYESStopDATAstatement.marker?stepExecuteprogramNOstatements.Definestartstop,andincrementvalues.Setdoindex=starttostopbyincrement;INDEX=start.SASstatementsend;ExecuteadditionalYESIsINDEXprogramstatements.outofrange?NOOutputobservationtoSASdataset.Executestatementsinloop.INDEX=INDEX+Increment24 7.1DOLoopProcessing7-11DOLoopLogic 7-12Chapter7ProcessingDataIterativelyPerformingRepetitiveCalculationsOnJanuary1ofeachyear,$5,000isinvestedinanaccount.Determinethevalueoftheaccountafterthreeyearsbasedonaconstantannualinterestrateof7.5percent.datainvest;doYear=2001to2003;Capital+5000;Capital+(Capital*.075);end;run;25RepetitiveCalculations:Compilationdatainvest;doYear=2001to2003;Capital+5000;Capital+(Capital*.075);end;run;PDVRDYearCapital_N_026... 7.1DOLoopProcessing7-13RepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;Capital+(Capital*.075);end;run;InitializePDVtomissingPDVRDYearCapital_N_.0127...RepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;IsYearCapital+(Capital*.075);end;outofrun;range?PDVRDYearCapital_N_20010128... 7-14Chapter7ProcessingDataIterativelyRepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;Capital+(Capital*.075);end;run;0+5000PDVRDYearCapital_N_20015000129...RepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;Capital+(Capital*.075);end;run;5000+(5000*.075)PDVRDYearCapital_N_20015375130... 7.1DOLoopProcessing7-15RepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;Capital+(Capital*.075);end;run;Year+1PDVRDYearCapital_N_20025375131...RepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;IsYearCapital+(Capital*.075);end;outofrun;range?PDVRDYearCapital_N_20025375132... 7-16Chapter7ProcessingDataIterativelyRepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;Capital+(Capital*.075);end;run;5375+5000PDVRDYearCapital_N_200210375133...RepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;Capital+(Capital*.075);end;run;10375+(10375*.075)PDVRDYearCapital_N_200211153.13134... 7.1DOLoopProcessing7-17RepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;Capital+(Capital*.075);end;run;Year+1PDVRDYearCapital_N_200311153.13135...RepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;IsYearCapital+(Capital*.075);end;outofrun;range?PDVRDYearCapital_N_200311153.13136... 7-18Chapter7ProcessingDataIterativelyRepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;Capital+(Capital*.075);end;run;11153.13+5000PDVRDYearCapital_N_200316153.13137...RepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;Capital+(Capital*.075);end;run;16153.13+(16153.13*.075)PDVRDYearCapital_N_200317364.61138... 7.1DOLoopProcessing7-19RepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;Capital+(Capital*.075);end;run;Year+1PDVRDYearCapital_N_200417364.61139...RepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;IsYearCapital+(Capital*.075);end;outofrun;range?PDVRDYearCapital_N_200417364.61140... 7-20Chapter7ProcessingDataIterativelyRepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;Capital+(Capital*.075);end;run;PDVRDYearCapital_N_200417364.61141...RepetitiveCalculations:Executiondatainvest;doYear=2001to2003;Capital+5000;Capital+(Capital*.075);end;run;AutomaticoutputPDVRDYearCapital_N_200417364.611Writeobservationtoinvest.42 7.1DOLoopProcessing7-21PerformingRepetitiveCalculationsprocprintdata=investnoobs;run;PROCPRINTOutputYearCapital200417364.6143PerformingRepetitiveCalculationsGenerateaseparateobservationforeachyear.datainvest;doYear=2001to2003;Capital+5000;Capital+(Capital*.075);output;end;run;procprintdata=investnoobs;run;c07s1d1.sas44 7-22Chapter7ProcessingDataIterativelyPerformingRepetitiveCalculationsPROCPRINTOutputYearCapital20015375.00200211153.13200317364.61WhyisthevalueofYearnotequalto2004inthelastobservation?45ReducingRedundantCodeRecalltheexamplethatforecaststhegrowthofeachdivisionofanairline.PartialListingofprog2.growthNumDivisionEmpsIncreaseAPTOPS2050.075FINACE1980.040FLTOPS1870.08046 7.1DOLoopProcessing7-23AForecastingApplication(Review)dataforecast;setprog2.growth(rename=(NumEmps=NewTotal));Year=1;NewTotal=NewTotal*(1+Increase);output;Year=2;NewTotal=NewTotal*(1+Increase);output;Year=3;NewTotal=NewTotal*(1+Increase);output;run;Whatifyouwanttoforecastgrowthoverthenext30years?47ReducingRedundantCodeUseaDOlooptoeliminatetheredundantcodeinthepreviousexample.dataforecast;setprog2.growth(rename=(NumEmps=NewTotal));doYear=1to3;NewTotal=NewTotal*(1+Increase);output;end;run;c07s1d2.sas48 7-24Chapter7ProcessingDataIterativelyReducingRedundantCodeprocprintdata=forecastnoobs;run;PartialPROCPRINTOutputNewDivisionTotalIncreaseYearAPTOPS220.380.0751APTOPS236.900.0752APTOPS254.670.0753FINACE205.920.0401WhatifyouwanttoforecastthenumberofyearsitwouldtakeforthesizeoftheAirportOperationsDivisiontoexceed300people?49ConditionalIterativeProcessingYoucanuseDOWHILEandDOUNTILstatementstostoptheloopwhenaconditionismetratherthanwhentheindexvariableexceedsaspecificvalue.Toavoidinfiniteloops,besurethattheconditionspecifiedwillbemet.50 7.1DOLoopProcessing7-25TheDOWHILEStatementTheDOWHILEstatementexecutesstatementsinaDOloopwhileaconditionistrue.DOWHILEDOWHILE((expressionexpression););additionalSASstatementsadditionalSASstatementsENDEND;;expressionisevaluatedatthetopoftheloop.Thestatementsintheloopneverexecuteifexpressionisinitiallyfalse.51TheDOUNTILStatementTheDOUNTILstatementexecutesstatementsinaDOloopuntilaconditionistrue.DOUNTILDOUNTIL((expressionexpression););additionalSASstatementsadditionalSASstatementsENDEND;;expressionisevaluatedatthebottomoftheloop.Thestatementsintheloopareexecutedatleastonce.52 7-26Chapter7ProcessingDataIterativelyConditionalIterativeProcessingDeterminethenumberofyearsitwouldtakeforanaccounttoexceed$1,000,000if$5,000isinvestedannuallyat7.5percent.53ConditionalIterativeProcessingdatainvest;dountil(Capital>1000000);Year+1;Capital+5000;Capital+(Capital*.075);end;run;procprintdata=investnoobs;run;54 7.1DOLoopProcessing7-27ConditionalIterativeProcessingPROCPRINTOutputCapitalYear1047355.9138HowcouldyougeneratethesameresultwithaDOWHILEstatement?55ConditionalIterativeProcessingdatainvest;dowhile(Capitalle1000000);Year+1;Capital+5000;Capital+(Capital*.075);end;run;procprintdata=investnoobs;run;56 7-28Chapter7ProcessingDataIterativelyTheIterativeDOStatementwithaConditionalClauseYoucancombineDOWHILEandDOUNTILstatementswiththeiterativeDOstatement.DODOindex-variableindex-variable==startstartTOTOstopstop>WHILEWHILE||UNTILUNTIL((expressionexpression););additionalSASstatementsadditionalSASstatementsENDEND;;ThisisonemethodofavoidinganinfiniteloopinDOWHILEorDOUNTILstatements.57InaDOWHILEstatement,theconditionalclauseischeckedaftertheindexvariableisincremented.InaDOUNTILstatement,theconditionalclauseischeckedbeforetheindexvariableisincremented.TheIterativeDOStatementwithaConditionalClauseDeterminethereturnoftheaccountagain.Stoptheloopif25yearsisreachedormorethan$250,000isaccumulated.58 7.1DOLoopProcessing7-29TheIterativeDOStatementwithaConditionalClausedatainvest;doYear=1to25until(Capital>250000);Capital+5000;Capital+(Capital*.075);end;run;procprintdata=investnoobs;run;59TheIterativeDOStatementwithaConditionalClausePROCPRINTOutputYearCapital21255594.8660 7-30Chapter7ProcessingDataIterativelyNestedDOLoopsNestedDOloopsareloopswithinloops.WhenyounestDOloops,¢usedifferentindexvariablesforeachloop¢becertainthateachDOstatementhasacorrespondingENDstatement.61NestedDOLoopsCreateoneobservationperyearforfiveyears,andshowtheearningsifyouinvest$5,000peryearwith7.5percentannualinterestcompoundedquarterly.62 7.1DOLoopProcessing7-31NestedDOLoopsdatainvest(drop=Quarter);doYear=1to5;Capital+5000;doQuarter=1to4;5x4xCapital+(Capital*(.075/4));end;output;end;run;procprintdata=investnoobs;run;63NestedDOLoopsPROCPRINTOutputYearCapital15385.68211186.79317435.37424165.94531415.68Howcouldyougenerateoneobservationforeachquarterlyamount?64 7-32Chapter7ProcessingDataIterativelyNestedDOLoopsComparethefinalresultsofinvesting$5,000ayearforfiveyearsinthreedifferentbanksthatcompoundquarterly.Assumeeachbankhasafixedinterestrate.prog2.banksNameRateCalhounBankandTrust0.0718StateSavingsBank0.0721NationalSavingsandTrust0.072865NestedDOLoopsdatainvest(drop=QuarterYear);setprog2.banks;Capital=0;doYear=1to5;Capital+5000;3xdoQuarter=1to4;5x4xCapital+(Capital*(Rate/4));end;end;run;Thisprogramissimilartothepreviousprogram.Thechangesarenoted.c07s1d3.sas66 7.1DOLoopProcessing7-33NestedDOLoops:Executiondatainvest(drop=QuarterYear);setprog2.banks;Capital=0;doYear=1to5;Capital+5000;doQuarter=1to4;Capital+(Capital*(Rate/4));(0.0718/4));end;end;run;PartialPDVDNameRate_N_CalhounBankandTrust0.0718167...NestedDOLoops:Executiondatainvest(drop=QuarterYear);setprog2.banks;Capital=0;doYear=1to5;Capital+5000;doQuarter=1to4;Capital+(Capital*(Rate/4));(0.0721/4));end;end;run;PartialPDVDNameRate_N_StateSavingsBank0.0721268... 7-34Chapter7ProcessingDataIterativelyNestedDOLoops:Executiondatainvest(drop=QuarterYear);setprog2.banks;Capital=0;doYear=1to5;Capital+5000;doQuarter=1to4;Capital+(Capital*(Rate/4));(0.0728/4));end;end;run;PartialPDVDNameRate_N_NationalSavingsandTrust0.0728369NestedDOLoopsprocprintdata=investnoobs;run;PROCPRINTOutputNameRateCapitalCalhounBankandTrust0.071831106.73StateSavingsBank0.072131135.55NationalSavingsandTrust0.072831202.9170 7.1DOLoopProcessing7-35Exercises1.PerformingComputationswithDOLoopsThepayrolldepartmentmustprojecttotalemployeecosts(wages,retirement,benefits,andmedicalbenefits)throughfutureyearsbasedonassumedincreases.a.CreateaSASdatasetnamedfuturewithfourvariables:Yearandthethreevariablesshownbelow.Initializeeachofthevariablesbelowtotheircurrentvalues,anduseaDOlooptocalculatetheirestimatedvaluesforthenexttenyears.Forexample,nextyear’swageexpensewillbethisyear’swageexpenseplus6percentofthisyear’samount;intwoyears,thewageexpensewillbenextyear’samountplus6percent;andsoon.Createoneobservationforeachyear.EstimatedannualVariableCurrentvalueincreaseWages$12,874,0006.0%Retire1,765,0001.4%Medical649,0009.5%UseSASdatefunctionstoguaranteethatthevalueofYearinthefirstobservationistheupcomingyear,regardlessofthecurrentyear.(Ifthecurrentyearis2001,thevalueofYearinthefirstobservationwillbe2002.Iftheprogramisrunin2006withoutanymodifications,thevalueofYearinthefirstobservationwillbe2007.)Printthedatasettoverifyyourresults.ObsYearWagesRetireMedical1200813646440.001789710.00710655.002200914465226.401814765.94778167.233201015333139.981840172.66852093.114201116253128.381865935.08933041.965201217228316.091892058.171021680.946201318262015.051918546.991118740.637201419357735.951945406.641225020.998201520519200.111972642.341341397.999201621750352.122000259.331468830.8010201723055373.252028262.961608369.72!TheresultsaboveweregeneratedonJanuary10,2007.YourvaluesforYearmightdiffer. 7-36Chapter7ProcessingDataIterativelyb.ModifythepreviousprogramtocreateanewvariablenamedTotCostthatisthesumofthewage,retirement,andmedicalcostsforeachyear.Printthedataset.ObsYearWagesRetireMedicalTotCost1200813646440.001789710.00710655.0016146805.002200914465226.401814765.94778167.2317058159.573201015333139.981840172.66852093.1118025405.764201116253128.381865935.08933041.9619052105.425201217228316.091892058.171021680.9420142055.206201318262015.051918546.991118740.6321299302.677201419357735.951945406.641225020.9922528163.598201520519200.111972642.341341397.9923833240.449201621750352.122000259.331468830.8025219442.2410201723055373.252028262.961608369.7226692005.93!TheresultsaboveweregeneratedonJanuary10,2007.YourvaluesforYearmightdiffer.c.Corporateincomeforlastyearwas$50,000,000.Incomeisprojectedtoincreaseat1percentperyear.ModifythepreviousprogramsothattheDOloopstopswhentheyear’stotalcostsexceedtheyear’sincome.Printthedatasettoverifythattotalcostsexceedincomeafter26observations.ObsYearIncomeTotCost1200850500000.0016146805.002200951005000.0017058159.573201051515050.0018025405.764201152030200.5019052105.425201252550502.5120142055.206201353076007.5321299302.677201453606767.6122528163.598201554142835.2823833240.449201654684263.6325219442.2410201755231106.2726692005.9311201855783417.3328256519.1312201956341251.5129918944.7513202056904664.0231685647.2914202157473710.6633563421.1315202258048447.7735559520.9116202358628932.2537681694.1417202459215221.5739938216.3018202559807373.7842337928.4919202660405447.5244890278.0120202761009502.0047605361.8921202861619597.0250493973.8122202962235792.9953567654.5723203062858150.9256838746.3024203163486732.4360320451.0325203264121599.7564026893.5626203364762815.7567973189.29!TheresultsaboveweregeneratedonJanuary10,2007.YourvaluesforYearmightdiffer. 7.2SASArrayProcessing7-377.2SASArrayProcessingObjectives¢UnderstandtheconceptsofSASarrays.¢UseSASarraystoperformrepetitivecalculations.73PerformingRepetitiveCalculationsEmployeescontributeanamounttocharityeveryquarter.TheSASdatasetprog2.donatecontainscontributiondataforeachemployee.Theemployersupplementseachcontributionby25percent.Calculateeachemployee’squarterlycontributionincludingthecompanysupplement.PartialListingofprog2.donateIDQtr1Qtr2Qtr3Qtr4E00224123322.E003673548403074 7-38Chapter7ProcessingDataIterativelyPerformingRepetitiveCalculationsdatacharity;setprog2.donate;Qtr1=Qtr1*1.25;Qtr2=Qtr2*1.25;Qtr3=Qtr3*1.25;Qtr4=Qtr4*1.25;run;procprintdata=charitynoobs;run;75PerformingRepetitiveCalculationsPartialPROCPRINTOutputIDQtr1Qtr2Qtr3Qtr4E0022415.0041.2527.50.E0036743.7560.0050.0037.50E00441.78.75111.25112.50E0058720.0023.7537.5036.25E005985.0010.007.501.25Whatifyouwanttosimilarlymodify52weeksofdatastoredinWeek1throughWeek52?76 7.2SASArrayProcessing7-39ArrayProcessingYoucanusearraystosimplifyprogramsthat¢performrepetitivecalculations¢createmanyvariableswiththesameattributes¢readdata¢rotateSASdatasetsbymakingvariablesintoobservationsorobservationsintovariables¢comparevariables¢performatablelookup.77WhatIsaSASArray?ASASarray¢isatemporarygroupingofSASvariablesthatarearrangedinaparticularorder¢isidentifiedbyanarrayname¢existsonlyforthedurationofthecurrentDATAstep¢isnotavariable.78!SASarraysaredifferentfromarraysinmanyotherprogramminglanguages.IntheSASSystem,anarrayisnotadatastructure.Itissimplyaconvenientwayoftemporarilyidentifyingagroupofvariables. 7-40Chapter7ProcessingDataIterativelyWhatIsaSASArray?Eachvalueinanarrayis¢calledanelement¢identifiedbyasubscriptthatrepresentsthepositionoftheelementinthearray.Whenyouuseanarrayreference,thecorrespondingvalueissubstitutedforthereference.79WhatIsaSASArray?ArraynameCONTRIBCONTRIBIDQtr1Qtr2Qtr3Qtr4DFirstSecondThirdFourthelementelementelementelement80... 7.2SASArrayProcessing7-41WhatIsaSASArray?ArraynameCONTRIBCONTRIBIDQtr1Qtr2Qtr3Qtr4FirstSecondThirdFourthelementelementelementelementCONTRIB{1}CONTRIB{2}CONTRIB{3}CONTRIB{4}Arrayreferences81 7-42Chapter7ProcessingDataIterativelyTheARRAYStatementTheARRAYstatementdefinestheelementsinanarray.Theseelementscanbeprocessedasagroup.Yourefertoelementsofthearraybythearraynameandsubscript.ARRAYARRAYarray-namearray-name{{subscriptsubscript}<$><}<$>><<(><(initial-value-listinitial-value-list)>)>;;82array-namespecifiesthenameofthearray.{subscript}describesthenumberandarrangementofelementsinthearraybyusinganasterisk,anumber,orarangeofnumbers.subscriptisenclosedinbraces({}).Brackets([])andparentheses(())arealsoallowed.subscriptoftenhastheform{dimension-size(s)}.{dimension-size(s)}isusedtoindicateanumericrepresentationofeitherthenumberofelementsinaone-dimensionalarrayorthenumberofelementsineachdimensionofamultidimensionalarray.$indicatesthattheelementsinthearrayarecharacterelements.Thedollarsignisnotnecessaryiftheelementsinthearraywerepreviouslydefinedascharacterelements.lengthspecifiesthelengthofelementsinthearraythatwerenotpreviouslyassignedalength.array-elementsnamestheelementsthatmakeupthearray.Arrayelementscanbelistedinanyorder.(initial-value-list)givesinitialvaluesforthecorrespondingelementsinthearray.Thevaluesforelementscanbenumbersorcharacterstrings.Youmustencloseallcharacterstringsinquotationmarks.!ArraynamescannotbeusedinLABEL,FORMAT,DROP,KEEP,orLENGTHstatements.Ifyouuseafunctionnameasthenameofthearray,SAStreatsparentheticalreferencesthatinvolvethenameasarrayreferences,notfunctionreferences,forthedurationoftheDATAstep. 7.2SASArrayProcessing7-43TheARRAYStatementTheARRAYstatement¢mustcontainallnumericorallcharacterelements¢mustbeusedtodefineanarraybeforethearraynamecanbereferenced¢createsvariablesiftheydonotalreadyexistinthePDV¢isacompile-timestatement.83!YoucanusespecialSASnameliststoreferencevariablesthatwerepreviouslydefinedinthesameDATAstep.The_CHARACTER_variablelistscharactervaluesonly.The_NUMERIC_variablelistsnumericvaluesonly.Avoidusingthe_ALL_specialSASnamelisttoreferencevariables,becausetheelementsinanarraymustbeeitherallcharacterorallnumericvalues. 7-44Chapter7ProcessingDataIterativelyDefininganArrayWriteanARRAYstatementthatdefinesthefourquarterlycontributionvariablesaselementsofanarray.arrayContrib{4}Qtr1Qtr2Qtr3Qtr4;CONTRIBCONTRIBIDQtr1Qtr2Qtr3Qtr4FirstSecondThirdFourthelementelementelementelement84!Thefourvariables,Qtr1,Qtr2,Qtr3,andQtr4,cannowbereferencedviathearraynameContrib.DefininganArrayVariablesthatareelementsofanarraydonotneedtohavesimilar,related,ornumberednames.arrayContrib2{4}Q1Qrtr2ThrdQQtr4;CONTRIB2CONTRIB2IDQ1Qrtr2ThrdQQtr4FirstSecondThirdFourthelementelementelementelement85 7.2SASArrayProcessing7-45ProcessinganArrayArrayprocessingoftenoccurswithinDOloops.AniterativeDOloopthatprocessesanarraytypicallyhasthefollowingform:DODOindex-variableindex-variable=1=1TOTOnumber-of-elements-in-arraynumber-of-elements-in-array;;additionalSASstatementsadditionalSASstatementsusingarray-nameusingarray-name{{index-variableindex-variable}}……ENDEND;;Toexecutetheloopasmanytimesasthereareelementsinthearray,specifythatthevaluesofindex-variablerangefrom1tonumber-of-elements-in-array.86YoumusttellSASwhichvariableinthearraytouseineachiterationoftheloop.YoucanwriteprogrammingstatementssothattheindexvariableoftheDOloopisthesubscriptofthearrayreference(forexample,array-name{index-variable}).Whenthevalueoftheindexvariablechanges,thesubscriptofthearrayreference(andthereforethevariablethatisreferenced)alsochanges.Toprocessparticularelementsofanarray,specifythoseelementsastherangeoftheiterativeDOstatement.Bydefault,SASincludesindex-variableintheoutputdataset.UseaDROPstatementortheDROP=datasetoptiontopreventtheindexvariablefrombeingwrittentoyouroutputdataset. 7-46Chapter7ProcessingDataIterativelyProcessinganArrayarrayContrib{4}Qtr1Qtr2Qtr3Qtr4;doi=1to4;Contrib{i}=Contrib{i}*1.25;end;arrayValueofreferenceCONTRIB{i}CONTRIB{i}indexvariablei1234CONTRIB{1}CONTRIB{2}CONTRIB{3}CONTRIB{4}Qtr1Qtr2Qtr3Qtr4FirstSecondThirdFourth89elementelementelementelement!Thenameiisusedherefortheindexvariable.AnyvalidSASvariablenamecanbeused.PerformingRepetitiveCalculationsdatacharity(drop=i);setprog2.donate;arrayContrib{4}Qtr1Qtr2Qtr3Qtr4;doi=1to4;Contrib{i}=Contrib{i}*1.25;end;run;c07s2d1.sas90 7.2SASArrayProcessing7-47PerformingRepetitiveCalculationsdatacharity(drop=i);setprog2.donate;arrayContrib{4}Qtr1Qtr2Qtr3Qtr4;doi=1to4;Contrib{i}=Contrib{i}*1.25;Contrib{1}=Contrib{1}*1.25;end;run;Wheni=1Qtr1=Qtr1*1.25;91...PerformingRepetitiveCalculationsdatacharity(drop=i);setprog2.donate;arrayContrib{4}Qtr1Qtr2Qtr3Qtr4;doi=1to4;Contrib{i}=Contrib{i}*1.25;Contrib{2}=Contrib{2}*1.25;end;run;Wheni=2Qtr2=Qtr2*1.25;92... 7-48Chapter7ProcessingDataIterativelyPerformingRepetitiveCalculationsdatacharity(drop=i);setprog2.donate;arrayContrib{4}Qtr1Qtr2Qtr3Qtr4;doi=1to4;Contrib{i}=Contrib{i}*1.25;Contrib{3}=Contrib{3}*1.25;end;run;Wheni=3Qtr3=Qtr3*1.25;93...PerformingRepetitiveCalculationsdatacharity(drop=i);setprog2.donate;arrayContrib{4}Qtr1Qtr2Qtr3Qtr4;doi=1to4;Contrib{i}=Contrib{i}*1.25;Contrib{4}=Contrib{4}*1.25;end;run;Wheni=4Qtr4=Qtr4*1.25;94 7.2SASArrayProcessing7-49PerformingRepetitiveCalculationsprocprintdata=charitynoobs;run;PartialPROCPRINTOutputIDQtr1Qtr2Qtr3Qtr4E0022415.0041.2527.50.E0036743.7560.0050.0037.50E00441.78.75111.25112.50E0058720.0023.7537.5036.25E005985.0010.007.501.2595 7-50Chapter7ProcessingDataIterativelyExercises2.UsingArraysforRepetitiveComputationsAskiresorthasaweather-recordingdevicethatwritesanobservationtoaSASdataseteveryday.Eachobservationinthedatasetprog2.skicontainsthedateand24hourlyreadingsofthetemperatureindegreesFahrenheitstartingat1:00a.m.PartialListingofprog2.skiDateT1T2T3T4T5T6T7T8T9T10T11T1218FEB200023222020212426282829313119FEB200025252630313333353637394020FEB200031313029292829303031303021FEB200013151617192020212324262722FEB2000202223252627293133353636T13T14T15T16T17T18T19T20T21T22T23T24323231323133323129272625404142424342414038363432302928262523222119171513293031303031302723222120373837343231302624252120Createadatasetnamedcelsiusbyreadingtheprog2.skidataset.ConvertallofthetemperaturesstoredinT1throughT24toCelsiusbyusingthisformula:Celsiustemperature=5*(Fahrenheittemperature-32)/9TheseCelsiustemperatureswillbestoredinT1throughT24.(Youdonotneedtocreate24newvariablesfortheCelsiustemperatures.)CreateavariableCostthatcontainsthedailycostofrunningasnowmakingmachineifthemachineautomaticallyrunsforonehourwhenthedetectedtemperatureislowerthan2degreesCelsius.Itcosts$125.00perhourtorunthemachine.Printthedataset.Roundthetemperaturevaluestothefirstdecimalplace. 7.2SASArrayProcessing7-51PartialPROCPRINTOutputObsDateT1T2T3T4T5T6T7118FEB2000-5.0-5.6-6.7-6.7-6.1-4.4-3.3219FEB2000-3.9-3.9-3.3-1.1-0.60.60.6320FEB2000-0.6-0.6-1.1-1.7-1.7-2.2-1.7421FEB2000-10.6-9.4-8.9-8.3-7.2-6.7-6.7522FEB2000-6.7-5.6-5.0-3.9-3.3-2.8-1.7ObsT8T9T10T11T12T13T14T15T16T171-2.2-2.2-1.7-0.6-0.60.00.0-0.60.0-0.621.72.22.83.94.44.45.05.65.66.13-1.1-1.1-0.6-1.1-1.1-1.1-1.7-2.2-3.3-3.94-6.1-5.0-4.4-3.3-2.8-1.7-1.1-0.6-1.1-1.15-0.60.61.72.22.22.83.32.81.10.0ObsT18T19T20T21T22T23T24Cost10.60.0-0.6-1.7-2.8-3.3-3.9300025.65.04.43.32.21.10.012503-5.0-5.6-6.1-7.2-8.3-9.4-10.630004-0.6-1.1-2.8-5.0-5.6-6.1-6.730005-0.6-1.1-3.3-4.4-3.9-6.1-6.72375 7-52Chapter7ProcessingDataIteratively7.3UsingSASArraysObjectives¢UseSASarraystocreatenewvariables.¢UseSASarraystoperformatablelookup.¢UseSASarraystorotateaSASdataset.98CreatingVariableswithArraysCalculatethepercentagethateachquarter’scontributionrepresentsoftheemployee’stotalannualcontribution.Basethepercentageonlyontheemployee’sactualcontributionandignorethecompanycontributions.PartialListingofprog2.donateIDQtr1Qtr2Qtr3Qtr4E00224123322.E003673548403099 7.3UsingSASArrays7-53CreatingVariableswithArraysdatapercent(drop=i);setprog2.donate;Total=sum(ofQtr1-Qtr4);arrayContrib{4}Qtr1-Qtr4;arrayPercent{4};doi=1to4;Percent{i}=Contrib{i}/Total;end;run;ThesecondARRAYstatementcreatesfournumericvariables:Percent1,Percent2,Percent3,andPercent4.c07s3d1.sas100ThefirstARRAYstatementusestheexistingvariablesQtr1,Qtr2,Qtr3,andQtr4.InthatARRAYstatement,anumberedrangeSASvariablelistisused. 7-54Chapter7ProcessingDataIterativelyCreatingVariableswithArraysprocprintdata=percentnoobs;varIDPercent1-Percent4;formatPercent1-Percent4percent6.;run;PartialPROCPRINTOutputIDPercent1Percent2Percent3Percent4E0022418%49%33%.E0036723%31%26%20%E00441.26%37%37%E0058717%20%32%31%E0059821%42%32%5%101ThePERCENTw.dformatmultipliesvaluesby100,formatstheminthesamewayastheBESTw.dformat,andaddsapercentsign(%)totheendoftheformattedvalue.Negativevaluesareenclosedinparentheses.ThePERCENTw.dformatallowsroomforapercentsignandparentheses,evenifthevalueisnotnegative.CreatingVariableswithArraysCalculatethedifferenceineachemployee’sactualcontributionfromonequartertothenext.FirstSecondThirdPartialListingofdifferencedifferencedifferenceprog2.donateIDQtr1Qtr2Qtr3Qtr4E00224123322.E0036735484030104 7.3UsingSASArrays7-55CreatingVariableswithArraysdatachange(drop=i);setprog2.donate;arrayContrib{4}Qtr1-Qtr4;arrayDiff{3};doi=1to3;Diff{i}=Contrib{i+1}-Contrib{i};end;run;c07s3d2.sas105CreatingVariableswithArraysdatachange(drop=i);setprog2.donate;arrayContrib{4}Qtr1-Qtr4;arrayDiff{3};{i+1}doi=1to3;Diff{1}=Contrib{2}-Contrib{1};Diff{i}=Contrib{i+1}-Contrib{i};end;run;Wheni=1Diff1=Qtr2-Qtr1;106... 7-56Chapter7ProcessingDataIterativelyCreatingVariableswithArraysdatachange(drop=i);setprog2.donate;arrayContrib{4}Qtr1-Qtr4;arrayDiff{3};doi=1to3;Diff{2}=Contrib{3}-Contrib{2};Diff{i}=Contrib{i+1}-Contrib{i};end;run;Wheni=2Diff2=Qtr3-Qtr2;107...CreatingVariableswithArraysdatachange(drop=i);setprog2.donate;arrayContrib{4}Qtr1-Qtr4;arrayDiff{3};doi=1to3;Diff{3}=Contrib{4}-Contrib{3};Diff{i}=Contrib{i+1}-Contrib{i};end;run;Wheni=3Diff3=Qtr4-Qtr3;108 7.3UsingSASArrays7-57CreatingVariableswithArraysprocprintdata=changenoobs;varIDDiff1-Diff3;run;PartialPROCPRINTOutputIDDiff1Diff2Diff3E0022421-11.E0036713-8-10E00441.261E00587311-1E005984-2-5109 7-58Chapter7ProcessingDataIterativelyAssigningInitialValuesDeterminethedifferencebetweenemployeecontributionsandlastyear’saveragequarterlygoalsof$10,$15,$5,and$10peremployee.datacompare(drop=iGoal1-Goal4);setprog2.donate;arrayContrib{4}Qtr1-Qtr4;arrayDiff{4};arrayGoal{4}Goal1-Goal4(10,15,5,10);doi=1to4;Diff{i}=Contrib{i}-Goal{i};end;run;110Elementsandvaluesarematchedbyposition.Iftherearemorearrayelementsthaninitialvalues,theremainingarrayelementsareassignedmissingvaluesandSASissuesawarning.Youcanseparatethevaluesintheinitialvaluelistwitheitheracommaorablankspace.!Initialvaluesareretaineduntilanewvalueisassignedtothearrayelement.Thisisanexampleofasimpletablelookupprogram. 7.3UsingSASArrays7-59AssigningInitialValuesprocprintdata=comparenoobs;varIDDiff1Diff2Diff3Diff4;run;PartialPROCPRINTOutputIDDiff1Diff2Diff3Diff4E0022421817.E0036725333520E00441.488480E00587642519E00598-6-71-9111CreatingVariableswithArrays:CompilationPartialListingofprog2.donatedatacompare(drop=iGoal1-Goal4);setprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;arrayDiff{4};E00224123322.arrayGoal{4}Goal1-Goal4E0036735484030(10,15,5,10);doi=1to4;Diff{i}=Contrib{i}-Goal{i};end;PDVrun;IDQtr1Qtr2Qtr3Qtr4112... 7-60Chapter7ProcessingDataIterativelyCreatingVariableswithArrays:CompilationPartialListingofprog2.donatedatacompare(drop=iGoal1-Goal4);setprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;arrayDiff{4};E00224123322.arrayGoal{4}Goal1-Goal4E0036735484030(10,15,5,10);doi=1to4;Diff{i}=Contrib{i}-Goal{i};end;PDVrun;IDQtr1Qtr2Qtr3Qtr4Diff1Diff2Diff3Diff4113...CreatingVariableswithArrays:CompilationPartialListingofprog2.donatedatacompare(drop=iGoal1-Goal4);setprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;arrayDiff{4};E00224123322.arrayGoal{4}Goal1-Goal4E0036735484030(10,15,5,10);doi=1to4;Diff{i}=Contrib{i}-Goal{i};end;PDVrun;IDQtr1Qtr2Qtr3Qtr4Diff1Diff2Diff3Diff4Goal1Goal2Goal3Goal41015510114... 7.3UsingSASArrays7-61CreatingVariableswithArrays:CompilationPartialListingofprog2.donatedatacompare(drop=iGoal1-Goal4);setprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;arrayDiff{4};E00224123322.arrayGoal{4}Goal1-Goal4E0036735484030(10,15,5,10);doi=1to4;Diff{i}=Contrib{i}-Goal{i};end;PDVrun;IDQtr1Qtr2Qtr3Qtr4Diff1Diff2Diff3Diff4Goal1Goal2Goal3Goal4i1015510115...CreatingVariableswithArrays:CompilationPartialListingofprog2.donatedatacompare(drop=iGoal1-Goal4);setprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;arrayDiff{4};E00224123322.arrayGoal{4}Goal1-Goal4E0036735484030(10,15,5,10);doi=1to4;Diff{i}=Contrib{i}-Goal{i};end;PDVrun;IDQtr1Qtr2Qtr3Qtr4Diff1Diff2DDDDDDiff3Diff4Goal1Goal2Goal3Goal4i1015510116 7-62Chapter7ProcessingDataIterativelyPerformingaTableLookupYoucanusethekeyword_TEMPORARY_insteadofspecifyingvariablenameswhenyoucreateanarraytodefinetemporaryarrayelements.datacompare(drop=i);setprog2.donate;arrayContrib{4}Qtr1-Qtr4;arrayDiff{4};arrayGoal{4}_temporary_(10,15,5,10);doi=1to4;Diff{i}=Contrib{i}-Goal{i};end;run;c07s3d3.sas117Arraysoftemporaryelementsareusefulwhentheonlypurposeforcreatinganarrayistoperformacalculation.Topreservetheresultofthecalculation,assignittoavariable.!Temporarydataelementsdonotappearintheoutputdataset.Temporarydataelementvaluesarealwaysautomaticallyretained.PerformingaTableLookupprocprintdata=comparenoobs;varIDDiff1Diff2Diff3Diff4;run;PartialPROCPRINTOutputIDDiff1Diff2Diff3Diff4E0022421817.E0036725333520E00441.488480E00587642519E00598-6-71-9118 7.3UsingSASArrays7-63RotatingaSASDataSetRotating,ortransposing,aSASdatasetcanbeaccomplishedbyusingarrayprocessing.Whenadatasetisrotated,thevaluesofanobservationintheinputdatasetbecomevaluesofavariableintheoutputdataset.PartialListingofprog2.donateIDQtr1Qtr2Qtr3Qtr4E00224123322.E0036735484030119!TheTRANSPOSEprocedureisalsousedtocreateanoutputdatasetbyrestructuringthevaluesinaSASdataset,transposingselectedvariablesintoobservations.RotatingaSASDataSetPartialListingofprog2.donateIDQtr1Qtr2Qtr3Qtr4E00224123322.E0036735484030PartialListingofrotateIDQtrAmountE00224112E00224233E00224322E002244.E00367135E00367248E00367340E00367430120 7-64Chapter7ProcessingDataIterativelyRotatingaSASDataSetdatarotate(drop=Qtr1-Qtr4);setprog2.donate;arrayContrib{4}Qtr1-Qtr4;doQtr=1to4;Amount=Contrib{Qtr};output;end;run;c07s3d4.sas121RotatingaSASDataSet:Compilationdatarotate(drop=Qtr1-Qtr4);setprog2.donate;arrayContrib{4}Qtr1-Qtr4;doQtr=1to4;Amount=Contrib{Qtr};output;end;run;PDVDDDDIDQtr1Qtr2Qtr3Qtr4QtrAmountrotatedatasetIDQtrAmount122... 7.3UsingSASArrays7-65RotatingaSASDataSet:Executiondatarotate(drop=Qtr1-Qtr4);PartialListingofprog2.donatesetprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;doQtr=1to4;E00224123322.Amount=Contrib{Qtr};E0036735484030output;end;InitializePDVtomissingrun;PDVDDDDIDQtr1Qtr2Qtr3Qtr4QtrAmount......123...RotatingaSASDataSet:Executiondatarotate(drop=Qtr1-Qtr4);PartialListingofprog2.donatesetprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;doQtr=1to4;E00224123322.Amount=Contrib{Qtr};E0036735484030output;end;run;PDVDDDDIDQtr1Qtr2Qtr3Qtr4QtrAmountE00224123322...124... 7-66Chapter7ProcessingDataIterativelyRotatingaSASDataSet:Executiondatarotate(drop=Qtr1-Qtr4);PartialListingofprog2.donatesetprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;doQtr=1to4;E00224123322.Amount=Contrib{Qtr};E0036735484030output;end;run;PDVDDDDIDQtr1Qtr2Qtr3Qtr4QtrAmountE00224123322.1.125...RotatingaSASDataSet:Executiondatarotate(drop=Qtr1-Qtr4);PartialListingofprog2.donatesetprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;doQtr=1to4;E00224123322.Amount=Contrib{Qtr};E0036735484030output;end;run;Amount=Contrib{1};PDVDDDDIDQtr1Qtr2Qtr3Qtr4QtrAmountE00224123322.112126... 7.3UsingSASArrays7-67RotatingaSASDataSet:Executiondatarotate(drop=Qtr1-Qtr4);PartialListingofprog2.donatesetprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;doQtr=1to4;E00224123322.Amount=Contrib{Qtr};E0036735484030output;end;run;PDVDDDDIDQtr1Qtr2Qtr3Qtr4QtrAmountE00224123322.112rotatedatasetIDQtrAmountE00224112127...RotatingaSASDataSet:Executiondatarotate(drop=Qtr1-Qtr4);PartialListingofprog2.donatesetprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;doQtr=1to4;E00224123322.Amount=Contrib{Qtr};E0036735484030output;end;run;Amount=Contrib{2};PDVDDDDIDQtr1Qtr2Qtr3Qtr4QtrAmountE00224123322.233128... 7-68Chapter7ProcessingDataIterativelyRotatingaSASDataSet:Executiondatarotate(drop=Qtr1-Qtr4);PartialListingofprog2.donatesetprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;doQtr=1to4;E00224123322.Amount=Contrib{Qtr};E0036735484030output;end;run;PDVDDDDIDQtr1Qtr2Qtr3Qtr4QtrAmountE00224123322.233rotatedatasetIDQtrAmountE00224112E00224233129...RotatingaSASDataSet:Executiondatarotate(drop=Qtr1-Qtr4);PartialListingofprog2.donatesetprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;doQtr=1to4;E00224123322.Amount=Contrib{Qtr};E0036735484030output;end;run;Amount=Contrib{3};PDVDDDDIDQtr1Qtr2Qtr3Qtr4QtrAmountE002241233223322130... 7.3UsingSASArrays7-69RotatingaSASDataSet:Executiondatarotate(drop=Qtr1-Qtr4);PartialListingofprog2.donatesetprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;doQtr=1to4;E00224123322.Amount=Contrib{Qtr};E0036735484030output;end;run;PDVDDDDIDQtr1Qtr2Qtr3Qtr4QtrAmountE00224123322.322rotatedatasetIDQtrAmountE00224112E00224233E00224322131...RotatingaSASDataSet:Executiondatarotate(drop=Qtr1-Qtr4);PartialListingofprog2.donatesetprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;doQtr=1to4;E00224123322.Amount=Contrib{Qtr};E0036735484030output;end;run;Amount=Contrib{4};PDVDDDDIDQtr1Qtr2Qtr3Qtr4QtrAmountE00224123322.4.132... 7-70Chapter7ProcessingDataIterativelyRotatingaSASDataSet:Executiondatarotate(drop=Qtr1-Qtr4);PartialListingofprog2.donatesetprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;doQtr=1to4;E00224123322.Amount=Contrib{Qtr};E0036735484030output;end;run;PDVDDDDIDQtr1Qtr2Qtr3Qtr4QtrAmountE00224123322.4.rotatedatasetIDQtrAmountE00224112E00224233E00224322E002244.133...RotatingaSASDataSet:Executiondatarotate(drop=Qtr1-Qtr4);PartialListingofprog2.donatesetprog2.donate;IDQtr1Qtr2Qtr3Qtr4arrayContrib{4}Qtr1-Qtr4;doQtr=1to4;E00224123322.Amount=Contrib{Qtr};E0036735484030output;end;run;PDVAutomaticreturn.ContinueDDDDIDprocessingobservationsQtr1Qtr2Qtr3Qtr4QtrAmountE00224fromprog2.donate1233.22.5.rotatedatasetIDQtrAmountE00224112E00224233E00224322E002244.134 7.3UsingSASArrays7-71RotatingaSASDataSetprocprintdata=rotatenoobs;run;PartialPROCPRINTOutputIDQtrAmountE00224112E00224233E00224322E002244.E00367135E00367248E00367340E00367430135 7-72Chapter7ProcessingDataIterativelyExercises3.UsingArraystoCreateVariablesWriteaDATAstepthatreadstheSASdatasetprog2.donateandcreatesaSASdatasetnamedquarter.Calculatetheaveragecontributionforanemployeeacrossallfourquarters,andthencalculatethedifferencebetweeneachquarterlycontributionandtheaverage.Usearraystohelpperformthecalculation.PartialListingofprog2.donateIDQtr1Qtr2Qtr3Qtr4E00224123322.E0036735484030E00441.638990E0058716193029E005984861Printthedataset.Thedesiredreportisshownbelow.PartialPROCPRINTOutputObsIDAverageDiff1Diff2Diff3Diff41E0022422.3333-10.333310.6667-0.3333.2E0036738.2500-3.25009.75001.7500-8.25003E0044180.6667.-17.66678.33339.33334E0058723.5000-7.5000-4.50006.50005.50005E005984.7500-0.75003.25001.2500-3.7500 7.3UsingSASArrays7-734.UsingArraysforTableLookup(Optional)Adriver’slicenserenewaltestconsistsoftenmultiple-choicequestions.Eachquestionhasfivechoices(A-E).Eachday,alltestresultsareenteredintotheSASdatasetprog2.testansshownbelow.Eachobservationinprog2.testanscontainsasingleperson’sanswers.Listingofprog2.testansIDQ1Q2Q3Q4Q5Q6Q7Q8Q9Q10291192ACCBDEDBBA593137BCCEEDBAA721311ACCBDDEBBC345221BCCADBBCAD193920ACCBEEDBBA257672BCCBDDDBBA357899CCCBEEEBBA564332ACCBEEDBBA111033ACBDDDBBA445732CCCCEEDBBB824610BBEBEEDBBA774235ACCBEEDBBA943244CCCBEEDBBA647893ACCBEEEBBA432118ACCBEEDBBAThecorrectanswersforthequestionsareshownbelow:Question:12345678910Answer:ACCBEEDBBAReadprog2.testansanddeterminewhethereachpersonpassedorfailedthetest.Computeavariablescorethatcontainsthetotalcorrectanswersforeachperson.!Createatemporaryarrayfortheanswerkey. 7-74Chapter7ProcessingDataIterativelyIfapersonscores7orhigher,writetheobservationtoadatasetnamedpassed.Printthedatasettoverifythatthereare12observationsinpassed.PROCPRINTOutputObsIDQ1Q2Q3Q4Q5Q6Q7Q8Q9Q10Score1291192ACCBDEDBBA92593137BCCEEDBAA73193920ACCBEEDBBA104257672BCCBDDDBBA75357899CCCBEEEBBA86564332ACCBEEDBBA107445732CCCCEEDBBB78824610BBEBEEDBBA79774235ACCBEEDBBA1010943244CCCBEEDBBA911647893ACCBEEEBBA912432118ACCBEEDBBA10Ifapersonscoreslessthan7,writetheobservationtoadatasetnamedfailed.Printthedatasettoverifythattherearethreeobservationsinfailed.PROCPRINTOutputObsIDQ1Q2Q3Q4Q5Q6Q7Q8Q9Q10Score1721311ACCBDDEBBC62345221BCCADBBCAD23111033ACBDDDBBA6 7.4SolutionstoExercises7-757.4SolutionstoExercises1.PerformingComputationswithDOLoopsa.datafuture;Wages=12874000;Retire=1765000;Medical=649000;Year=year(today());dountil(Year=year(today())+10);Year+1;/*IfaDOUNTILstatementisused,youmustremembertoincrementthevalueofYear.*/Wages+(Wages*.06);Retire+(Retire*.014);Medical+(Medical*.095);output;end;run;procprintdata=future;varYearWagesRetireMedical;run;Alternatesolution:datafuture;Wages=12874000;Retire=1765000;Medical=649000;doYear=year(today())+1toyear(today())+10;Wages+(Wages*.06);Retire+(Retire*.014);Medical+(Medical*.095);output;end;run;procprintdata=future;varYearWagesRetireMedical;run; 7-76Chapter7ProcessingDataIterativelyb.datafuture;Wages=12874000;Retire=1765000;Medical=649000;Year=year(today());dountil(Year=year(today())+10);Year+1;/*IfaDOUNTILstatementisused,youmustremembertoincrementthevalueofYear.*/Wages+(Wages*.06);Retire+(Retire*.014);Medical+(Medical*.095);TotCost=sum(Wages,Retire,Medical);output;end;run;procprintdata=future;varYearWagesRetireMedicalTotCost;run;Alternatesolution:datafuture;Wages=12874000;Retire=1765000;Medical=649000;doYear=year(today())+1toyear(today())+10;Wages+(Wages*.06);Retire+(Retire*.014);Medical+(Medical*.095);TotCost=sum(Wages,Retire,Medical);output;end;run;procprintdata=future;varYearWagesRetireMedicalTotCost;run; 7.4SolutionstoExercises7-77c.datafuture;Year=year(today());Wages=12874000;Retire=1765000;Medical=649000;Income=50000000;dountil(TotCostgtIncome);Wages+(Wages*.06);Retire+(Retire*.014);Medical+(Medical*.095);TotCost=sum(Wages,Retire,Medical);Income+(Income*.01);Year+1;output;end;run;procprintdata=future;varYearIncomeTotCost;run;2.UsingArraysforRepetitiveComputationsdatacelsius(drop=i);setprog2.ski;/*Youmustresetcosttozeroeverytimeanobservationfromprog2.skiisread.*/Cost=0;arrayTemps{24}T1-T24;doi=1to24;Temps{i}=round(5*(Temps{i}-32)/9,.1);ifTemps{i}lt2thenCost+125;end;run;procprintdata=celsius;run; 7-78Chapter7ProcessingDataIteratively3.UsingArraystoCreateVariablesdataquarter(drop=Qtr);setprog2.donate;/*TwoARRAYstatementsarenecessary.ThefirstARRAYstatementcreatesaSASarraythatcontainsthefourquarterlycontributions.ThesecondARRAYstatementcreatesaSASarraythatcontainsthefourdifferencesthatwillbecalculatedduringtheDATAstep.*/arrayContrib{4}Qtr1-Qtr4;arrayDiff{4};Average=mean(ofQtr1-Qtr4);doQtr=1to4;Diff{Qtr}=Contrib{Qtr}-Average;end;run;procprintdata=quarter;varIDAverageDiff1-Diff4;run; 7.4SolutionstoExercises7-794.UsingArraysforTableLookup(Optional)datapassed(drop=i)failed(drop=i);setprog2.testans;/*TwoARRAYstatementsarenecessary.ThefirstARRAYstatementcreatesaSASarraythatcontainsthetenresponseseachtest-takerselected.ThesecondARRAYstatementcreatesaSASarraythatcontainsthetencorrectanswersforeachofthetenquestions.*/arrayResponse{10}Q1-Q10;arrayAnswer{10}$1_temporary_('A','C','C','B','E','E','D','B','B','A');Score=0;doi=1to10;ifAnswer{i}=Response{i}thenScore+1;end;ifScorege7thenoutputpassed;elseoutputfailed;run;procprintdata=passed;run;procprintdata=failed;run; 7-80Chapter7ProcessingDataIteratively Chapter8Combining®SASDataSets8.1Match-MergingTwoorMoreSASDataSets................................................................8-38.2SimpleJoinsUsingtheSQLProcedure(Self-Study)................................................8-278.3SolutionstoExercises.................................................................................................8-41 8-2Chapter8CombiningSAS®DataSets 8.1Match-MergingTwoorMoreSASDataSets8-38.1Match-MergingTwoorMoreSASDataSetsObjectives¢Performamatch-merge.¢Performexplicitoutputformatchingandnon-matchingobservations.3MergingDataSetsAmergecombinestwoormoreexistingdatasetsbyjoiningobservationsside-by-side.DATAStep4 8-4Chapter8CombiningSAS®DataSetsMatch-MergeThemostcommontypeofmergeisamatch-merge,whichusesacommonvariabletojoinobservations.DATAStep5Match-MergingWhenyoumatch-mergetwoormoredatasets,itiscommontohave¢repeatedBYvalues¢non-matches.6 8.1Match-MergingTwoorMoreSASDataSets8-5Match-MergingThedatasetprog2.transactcontainsanaccountnumberandinformationontransactionsforaweek.Thedatasetprog2.branchescontainsanaccountnumberandthebranchlocationforthataccount.ActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wacker7DesiredOutputThebankmanagerwantstoseereportsbasedonthreedatasets.Goal:Adatasetnamednewtransthatshowsthisweek’stransactions.ActNumTransAmntBranch56891D126.32N.Lincoln56891C560N.Lincoln58876D14.56W.Argyle59987C371.69E.Wacker8 8-6Chapter8CombiningSAS®DataSetsDesiredOutputGoal:Adatasetnamednoactivthatshowsaccountswithnotransactionsthisweek.ActNumBranch56900S.Cicero59900N.Damen9DesiredOutputGoal:Adatasetnamednoacctthatshowstransactionswithnomatchingaccountnumber.ActNumTransAmnt57900C23510 8.1Match-MergingTwoorMoreSASDataSets8-7TheMERGEStatementYoucanusetheMERGEstatementtocombineobservationsfromtwoormoreSASdatasets.GeneralformoftheMERGEstatementwithaBYstatement:DATADATASAS-data-setSAS-data-set……;;MERGEMERGESAS-data-set-1SAS-data-set-2SAS-data-set-1SAS-data-set-2……;;BYBYBY-variable-1...BY-variable-1...;;<>RUN;RUN;11!ThereisnolimitonthenumberofdatasetsthatcanbemergedinoneDATAstep.TheSORTProcedure(Review)WhenyouusetheBYstatementwithaMERGEstatement,thedatasetmustbesortedorindexedaccordingtotheBYvariable(s).YoucanusetheSORTproceduretosortthedata.GeneralformofaPROCSORTstep:PROCSORTPROCSORTDATA=DATA=SAS-data-set1SAS-data-set1SAS-data-set2>;;BYBYBY-variable...BY-variable...;;RUN;RUN;12!IfyoumergeaSASdatasetwithaDBMStablefromanotherdatabase,theDBMStabledoesnothavetobesorted. 8-8Chapter8CombiningSAS®DataSetsDATAStepMergeABIDNamedatanew;IDAge1SAMmergeab;1313SUEbyID;2424BOBrun;421NEWIDNameAge1SAM312423SUE4BOB2113IdentifyingDataSetContributorsWhenyoureadmultipleSASdatasetsinoneDATAstep,youcanusetheIN=datasetoptiontodetectwhichdatasetcontributedtoanobservation.GeneralformoftheIN=datasetoption:SAS-data-setSAS-data-set(IN=(IN=variablevariable))wherevariableisanyvalidSASvariablename.14 8.1Match-MergingTwoorMoreSASDataSets8-9TheIN=DataSetOptionvariableisatemporarynumericvariablewithavalueof0toindicatefalse;thedatasetdidnotcontributetothecurrentobservation1toindicatetrue;thedatasetdidcontributetothecurrentobservation.VariablescreatedusingIN=areautomaticallydroppedfromtheoutputdataset.15UsingtheIN=DataSetOptiondatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;run;16 8-10Chapter8CombiningSAS®DataSetsIftheObservationIsaMatchprog2.transactandprog2.branchesbothcontributedtotheobservation.InTrans=1andInBanks=1prog2.transactprog2.branchesCurrentObservation17IftheObservationIsNotaMatchprog2.branchescontributedtotheobservation.prog2.transactdidnot.(Theaccounthadnotransactionsthisweek.)InTrans=0andInBanks=1prog2.transactprog2.branchesCurrentObservation18 8.1Match-MergingTwoorMoreSASDataSets8-11IftheObservationIsNotaMatchprog2.transactcontributedtotheobservation.prog2.branchesdidnot.(Atransactionoccurred,buttheaccountnumberwasinvalid.)InTrans=1andInBanks=0prog2.transactprog2.branchesCurrentObservation19UsingIN=toIdentifyMatchesandNon-Matchesdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;c08s1d1.sas20 8-12Chapter8CombiningSAS®DataSetsIdentifyingDataSetContributors:Compilationdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DPDVDInTransActNumTransAmntInBanksBranch21...IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;InitializePDVtomissingelseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch0.022... 8.1Match-MergingTwoorMoreSASDataSets8-13IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.32568915689156891N.Lincoln568915689156891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.WackerWhichBYgroupcomesfirst?datanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;TheymatchTheymatchelseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch0.023...IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch156891D126.32024... 8-14Chapter8CombiningSAS®DataSetsIdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch156891D126.321N.Lincoln25...IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;TrueifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch156891D126.321N.Lincoln26... 8.1Match-MergingTwoorMoreSASDataSets8-15IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;Explicitrun;DDoutputInTransActNumTransAmntInBanksBranch156891D126.321N.Lincoln27Writeobservationtonewtrans....IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranchAutomatic156891D126.321N.Lincolnreturn28... 8-16Chapter8CombiningSAS®DataSetsIdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.CiceroYesYesNONO57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.WackerAnyobsremainingdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);incurrentBYmergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);group?byActNum;ifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch156891D126.321N.Lincoln29...IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;DonotreinitializePDVtomissingelseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch156891D126.321N.Lincoln30... 8.1Match-MergingTwoorMoreSASDataSets8-17IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero568915689157900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.WackerWhichBYgroupdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);comesfirst?mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch156891D126.321N.Lincoln31...IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch156891C5601N.Lincoln32... 8-18Chapter8CombiningSAS®DataSetsIdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;TrueifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch156891D5601N.Lincoln33...IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;Explicitrun;DDoutputInTransActNumTransAmntInBanksBranch156891D5601N.Lincoln34Writeobservationtonewtrans.... 8.1Match-MergingTwoorMoreSASDataSets8-19IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranchAutomatic156891D5601N.Lincolnreturn35...IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.CiceroNONO57900C23558876W.ArgyleNONO58876D14.5659900N.Damen59987C371.6959987E.WackerAnyobsremainingdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);incurrentBYmergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);group?byActNum;ifInTransandInBanksthenoutputnewtrans;ReinitializePDVtomissingelseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch0.036... 8-20Chapter8CombiningSAS®DataSetsIdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero569005690057900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.WackerWhichBYgroupdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);comesfirst?mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch0.037...IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch056900.1S.Cicero38... 8.1Match-MergingTwoorMoreSASDataSets8-21IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;FalseifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch056900.1S.Cicero39...IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;TrueifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch056900.1S.Cicero40... 8-22Chapter8CombiningSAS®DataSetsIdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDExplicitInTransActNumTransAmntInBanksBranchoutput056900.1S.Cicero41Writeobservationtonoactiv....IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);byActNum;ifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranchAutomatic056900.1S.Ciceroreturn42... 8.1Match-MergingTwoorMoreSASDataSets8-23IdentifyingDataSetContributors:Executionprog2.transactprog2.branchesActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.Wackerdatanewtransnoactiv(drop=TransAmnt)noacct(drop=Branch);mergeprog2.transact(in=InTrans)prog2.branches(in=InBanks);ContinueprocessingbyActNum;untilendofbothdatasetsifInTransandInBanksthenoutputnewtrans;elseifInBanksandnotInTransthenoutputnoactiv;elseifInTransandnotInBanksthenoutputnoacct;run;DDInTransActNumTransAmntInBanksBranch056900.1S.Cicero43ViewingOnlytheMatchesprocprintdata=newtransnoobs;run;PROCPRINTOutputActNumTransAmntBranch56891D126.32N.Lincoln56891C560N.Lincoln58876D14.56W.Argyle59987C371.69E.Wacker44 8-24Chapter8CombiningSAS®DataSetsNon-Matchesfromprog2.branchesprocprintdata=noactivnoobs;run;PROCPRINTOutputActNumBranch56900S.Cicero59900N.Damen45Non-Matchesfromprog2.transactprocprintdata=noacctnoobs;run;PROCPRINTOutputActNumTransAmnt57900C235c08s1d1.sas46 8.1Match-MergingTwoorMoreSASDataSets8-25Exercises1.Match-MergingTwoDataSetsThedatasetprog2.pricesisamasterdatasetcontainingaproductcode(ProdCode)andaunitprice(Price)foreachproductsoldbyaparticularcompany.TheSASdatasetprog2.todaysalescontainsaproductcodeandquantitysoldforeachsalemadeonagivenday.PartialListingofprog2.pricesProdCodePrice1723789.6429978114.4710496128.990884912.2333060162.9905846107.7427731140.753096738.7316344181.5111220160.49PartialListingofprog2.todaysalesProdCodeQty17237515078231049615330601330602333060163306030058461305846130584610!Thetwodatasetsarenotsorted. 8-26Chapter8CombiningSAS®DataSetsCreatethreedatasets:•Adatasetnamedrevenuethatcontainstheproductcode(ProdCode),theprice(Price),thequantitysold(Qty),andtherevenuegeneratedfromeachsale(Revenue).RevenueisanewvariablethatisequaltoPrice*Qty.•Adatasetnamednotsoldthatcontainstheproductcode(ProdCode)andprice(Price)foreachproductthatwasnotsold.•Adatasetnamedinvalidcodethatcontainstheproductcode(ProdCode)andquantity(Qty)foreachobservationinthetodaysalesdatasetthatdoesnothaveacorrespondingproductcodeinthepricesdataset.Thedatasetsshouldcontain39,7,and4observations,respectively.PartialListingofrevenueDataSet(shouldhave39observations)ProdObsCodePriceQtyRevenue10528853.2616852.1620528853.26191011.94305846107.74131400.62405846107.74131400.62505846107.74101077.4060876640.9613532.48710496128.99151934.85811220160.49132086.37ListingofnotsoldDataSet(shouldhave7observations)ProdObsCodePrice104333114.3620884912.2331121169.16417183164.82529978114.4763033931.7473096738.73ListingofinvalidcodeDataSet(shouldhave4observations)ProdObsCodeQty1114651321255673150782342627810 8.2SimpleJoinsUsingtheSQLProcedure(Self-Study)8-278.2SimpleJoinsUsingtheSQLProcedure(Self-Study)Objectives¢PerformaninnerjoinusingtheSQLprocedure.49 8-28Chapter8CombiningSAS®DataSetsTheSQLProcedureTheSQLprocedureenablesyoutowriteANSIstandardSQLcodewithintheSASSystemanduseittoprocessSAStables.50!ThissectioncoversbasicSQLsyntaxforaninnerjoin.TolearnmoreabouttheSQLprocedure,seetheSASdocumentation.SASEducationalsooffersanSQLcoursetitledSQLProcessing®withtheSASSystem(http://www.sas.com/apps/wtraining2/coursedetails.jsp?course_code=sql&ctry=us).PROCSQLversustheDATAStep:BenefitsTheSQLprocedureenablesyouto¢jointablesandproduceareportinonestepwithoutcreatingaSASdataset¢jointableswithoutsorteddata¢usecomplexmatchingcriteria.Bydefault,PROCSQLreturnsareport,notaSASdataset.51 8.2SimpleJoinsUsingtheSQLProcedure(Self-Study)8-29PROCSQLversustheDATAStep:CostsIngeneral,theSQLprocedurerequiresmoreCPUtimeandmemorythanaDATAstepmerge.52JoiningTwoTableswithPROCSQLActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891C56056900S.Cicero57900C23558876W.Argyle58876D14.5659900N.Damen59987C371.6959987E.WackerThetableprog2.transcontainsanaccountnumberandinformationontransactionsforaweek.Thetableprog2.branchescontainsanaccountnumberandthebranchlocationforthataccount.53 8-30Chapter8CombiningSAS®DataSetsDesiredOutputThebankmanagerwantstoseeonlytheaccountsthathavevalidtransactions(onlyrowswithmatchingvaluesofActNum).ActNumTransAmntBranchƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ56891D126.32N.Lincoln56891C560N.Lincoln58876D14.56W.Argyle59987C371.69E.Wacker54TheSQLProcedure:SyntaxOverviewThePROCSQLstatementsignalsthestartoftheSQLprocedure.PROCSQL;PROCSQL;55 8.2SimpleJoinsUsingtheSQLProcedure(Self-Study)8-31TheSQLProcedure:SyntaxOverviewTheQUITstatementendstheSQLstep.QUIT;QUIT;56TheSQLProcedure:SyntaxOverviewStatementswithintheSQLstep(alsocalledqueries)aremadeofsmallerbuildingblockscalledclauses.Thefollowingclausesarediscussedinthissection:¢SELECT¢FROM¢WHEREThereisonesemicolonattheendofeachquery,notattheendofeachclause.57 8-32Chapter8CombiningSAS®DataSetsTheSELECTClauseTheSELECTclauseidentifiescolumnstoincludeinthequeryresultortable.SELECTSELECTvar-1var-1,,var-2...var-2...ColumnslistedintheSELECTclauseareseparatedbycommas.Thereisnocommafollowingthelastvariableinthelist.SELECTSELECT**Toselectallcolumnsread,useanasteriskinplaceofthecolumnnames.58TheFROMClauseTheFROMclauseidentifiestheSAStable(s)fromwhichtoread.FROMFROMSAS-data-set...SAS-data-set...59 8.2SimpleJoinsUsingtheSQLProcedure(Self-Study)8-33UsingPROCSQLtoJoinTablesTojointwoormoreSAStables,listthemintheFROMclauseseparatedbycommas.GeneralformofanSQLjoin:PROCSQL;PROCSQL;SELECTSELECTvar-1var-1,,var-2var-2……FROMFROMSAS-data-set-1SAS-data-set-1,,SAS-data-set-2...SAS-data-set-2...;;60!YoucanusePROCSQLtojoinasmanyas256datasets.SQLJoinswithoutaWHEREClauseAnSQLjoinspecifiedwithoutaWHEREclauseresultsinaCartesianproduct.Allpossiblecombinationsareoutput.procsql;select*fromprog2.trans,prog2.branches;quit;61 8-34Chapter8CombiningSAS®DataSetsSQLJoinwithoutaWHEREClausePartialOutputActActNumTransAmntNumBranch56891D126.3256891N.Lincoln56891D126.3256900S.Cicero56891D126.3258876W.Argyle56891D126.3259900N.Damen56891D126.3259987E.Wacker56891C56056891N.Lincoln56891C56056900S.Cicero56891C56058876W.Argyle56891C56059900N.Damen62TheWHEREClauseInajoin,theWHEREclausespecifiesthejoincriteria,WHEREWHEREexpressionexpressionwhereexpressionisanyvalidSAScondition.63 8.2SimpleJoinsUsingtheSQLProcedure(Self-Study)8-35JoiningonaCommonVariableThejoininthescenariorequiresonlymatchingvaluesofActNum.ActNumfromprog2.branches=ActNumfromprog2.trans64 8-36Chapter8CombiningSAS®DataSetsIdentifyingVariableswiththeSameNamesprocsql;selecttrans.ActNum,Trans,Amnt,Branchfromprog2.trans,prog2.brancheswheretrans.ActNum=branches.ActNum;quit;Youdonotneedtousethetablenameasaprefixifthecolumnnameappearsinonlyonetable.65!Conceptually,SASselectsmatchingrowsfromtheCartesianproduct.However,whenthecodeisactuallyprocessed,SASusestheWHEREcriteriatooptimizethejoin.BecausethejoinoutputsonlyrowswherethevaluesofActNummatch,youcanselectActNumfromeithertable.procsql;selectBranches.ActNum,Trans,Amnt,Branchfromprog2.trans,prog2.brancheswheretrans.ActNum=branches.ActNum;quit; 8.2SimpleJoinsUsingtheSQLProcedure(Self-Study)8-37AssigninganAliasforaSASTableYoucanalsospecifyanaliasforaSAStable.Thealiasreplacesthetablenameasthecolumnprefix.FROMFROMSAS-data-set-1AS>alias-1,alias-1,SAS-data-set-2AS>alias-2...alias-2...AnaliascanbeanyvalidSASname.66AssigninganAliasforaSASTableprocsql;selectT.ActNum,Trans,Amnt,Branchfromprog2.transasT,prog2.branchesasBwhereT.ActNum=B.ActNum;quit;c08s2d1.sas67Usually,thetablealiasisusedasaconvenience.Ifyoujointwotableswiththesametablenamebutdifferentlibraryreferences,youmustspecifyanalias. 8-38Chapter8CombiningSAS®DataSetsInnerJoinwithPROCSQLActNumTransAmntBranchƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒ56891D126.32N.Lincoln56891C560N.Lincoln58876D14.56W.Argyle59987C371.69E.Wackerc08s2d1.sas68 8.2SimpleJoinsUsingtheSQLProcedure(Self-Study)8-39Exercises2.PerformingSimpleJoinsUsingPROCSQL(Optional)TheSAStableprog2.rduschedulehasonerowrepresentingeachtimeaflightattendantorpilotisscheduledtoflyintoRDUairport.Itcontainstheflightnumber,thedateoftheflight,andtheemployee’sidentificationnumber.PartialListingofprog2.rduscheduleFltIDSchDateEmpIDIA0360003JAN2000E00075IA0360003JAN2000E00434IA0360003JAN2000E00481IA0240016JAN2000E00082IA0200320JAN2000E00082IA0200320JAN2000E00485IA0200523JAN2000E00481IA0240207FEB2000E00364TheSAStableprog2.fltsptsisamastertableofalltheflightattendantsandpilotsinthecompany.Itcontainseachemployee’sfirstname,lastname,identificationnumber,andjobcode.PartialListingofprog2.fltsptsJobFirstNameLastNameIDCodeDOROTHYEMILLSE00001FLTAT3J.KEVINCOCKERHAME00024FLTAT3DESIREEGOLDENBERGE00031PILOT3ALECFISHERE00033FLTAT2NORMAJEANWIELENGAE00043PILOT3GREGORYJ.GOODYEARE00046FLTAT1HANSECKHAUSENE00047FLTAT3JOHNK.MELTONE00052FLTAT2ANNEWHITEJR.E00055PILOT3 8-40Chapter8CombiningSAS®DataSetsUsePROCSQLtoproduceareportshowingalltheinformationfortheflightattendantsandpilotsscheduledtoflyintoRDU.PartialOutputJobEmpIDFirstNameLastNameCodeFltIDSchDateƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒƒE00434KATESMITHPILOT2IA0360003JAN2000E00481BETTYA.YANGFLTAT2IA0360003JAN2000E00481BETTYA.YANGFLTAT2IA0200523JAN2000E00377DONALDT.SZCZEPANSKIPILOT1IA0200016FEB2000E00207ANNEH.YANGFLTAT2IA0240517FEB2000E00432SANDRASCHOBERFLTAT2IA0240517FEB2000E00052JOHNK.MELTONFLTAT2IA0340003APR2000E00247CARRIED.DODGEPILOT2IA0340003APR2000E00120PEGGYH.DUNLAPFLTAT2IA0200005APR2000E00248DAWNB.EDWARDSFLTAT3IA0200005APR2000Hint:SQLjoinsdonotrequirekeycolumnstohavethesamename. 8.3SolutionstoExercises8-418.3SolutionstoExercises1.Match-MergingTwoDataSets/*EachdatasetmustbesortedbyProdCodebeforemerging*/procsortdata=prog2.pricesout=pricesort;byProdCode;run;procsortdata=prog2.todaysalesout=salesort;byProdCode;run;datarevenueNotSold(keep=PriceProdCode)InValidCode(Keep=ProdCodeQty);mergePriceSort(in=InPrice)SaleSort(in=InSales);byProdCode;ifInPriceandInSalesthendo;/*MatchingProdcodes*/Revenue=Qty*Price;/*Onlynecessarytocalculaterevenueformatches*/outputrevenue;end;elseifInPriceandnotInSalesthenoutputnotsold;/*ProductnotinTodaySalesdataset.*//*Ithasnotsoldthisweek*/elseoutputinvalidcode;/*ProductinTodaySalesthatisnotinthemasterpricelist.*/run;procprintdata=revenue;run;procprintdata=notsold;run;procprintdata=invalidcode;run; 8-42Chapter8CombiningSAS®DataSets2.PerformingSimpleJoinsUsingPROCSQL(Optional)procsql;selectEmpID,FirstName,LastName,JobCode,FltID,SchDatefromprog2.rduschedule,prog2.fltsptswhereEmpID=ID/*SQLdoesnotrequirekeyvariablestohavethesamename.*/;quit; Chapter9LearningMore9.1WhereDoIGoFromHere?............................................................................................9-39.2SASResources...............................................................................................................9-5 9-2Chapter9LearningMore 9.1WhereDoIGoFromHere?9-39.1WhereDoIGoFromHere?Objectives¢ExplorewhichSAStrainingcoursesareappropriateafteryoucompleteSAS®ProgrammingII:ManipulatingDatawiththeDATAStep.3SuggestedSASTrainingCoursesSAS®ProgrammingIII:AdvancedTechniquesincludestopicsthatyoucanusetobroadenyourprogrammingskills.SAS®MacroLanguageincludestopicsonbuildingcompletemacro-basedsystemsusingtheSASmacrofacility.4 9-4Chapter9LearningMoreSASCertifiedProfessionalProgramConsidertakingacertificationexamtoassessyourknowledgeofSASsoftware.Foracurrentlistingofcertificationexamsandregistrationinformation,visitsupport.sas.com/certify.5 9.2SASResources9-59.2SASResourcesServicesUserGroupsEducationDocumentationConsultingTechnicalSupport7EducationComputer-based:¢e-LearningConferences:¢DataMiningTechnologyConference8 9-6Chapter9LearningMoreEducationRefertotheSASTrainingWebsiteformoreinformationontheseclassesandthebroadcurriculumofcoursesavailable.support.sas.com/training9SASTrainingHomePagesupport.sas.com/training/us10 9.2SASResources9-7100%CustomerSatisfactionGuaranteeAtSASEducation,satisfactionis100%guaranteed.“AtSASEducationwetakegreatprideinthefactthatourcustomersconsistentlyrankourtrainingasexcellent.That’snoaccident.Fromthemomentyouregister,duringyourtraining,andevenafteryou'rebackatwork,westrivetoprovideyouwiththehighestlevelofcustomercarepossible.OurgoalistohelpyoulearnhowtouseSASmoreeffectively.So,ifyou’renotsatisfiedwithyourtrainingexperience,letusknowandwewillmakethingsright.Ipromise.”Dr.HerbertJ.Kirk,SASEducationVicePresident11ValueBeyondtheClassroomMorethan2,100SASstudentswhotooktraininginthefirstthreemonthsof2006weresurveyedtodeterminetheimpactofSAStrainingontheirjobperformance.Thesurveywasgivenbetween60and120daysbackonthejobtoallowafairjudgmentonhowSAStrainingmighthavehelpedthem.Herearesomeresults:MySASknowledgehasincreased.93%IwouldrecommendSAStrainingtoacolleague.93%ThetrainingIreceivedfromSASwasbetterthanothertrainingI'vetaken.81%Myproductivityhasincreased.69%Iammoreefficientafterhavingcompletedmytraining.61%12 9-8Chapter9LearningMoreConsultingServicesServicesprovidedincludethefollowing:¢knowledgetransfer¢applicationdevelopment¢analyticalconsulting¢implementbusinesssolutions13TechnicalSupportGoals:¢ProvidesupporttoSASuserstosolveanyproblemsthattheyencounterwhenusingSASsoftware.¢Freeunlimitedsupport.¢LocalsupportateachsitewithadesignatedSASconsultant.WorldWideWebServices:¢Report/resolveproblems¢Frequentlyaskedquestions¢SASwareBallotsuggestions/results¢Downloadzaps/fixes/patches¢Uploadcode/data¢SearchSASnotes¢Alertnotes14 9.2SASResources9-9TechnicalSupport(NorthAmerica)ProblemTrackingSystemTelephone:9:00a.m.until8:00p.m.EasternTimeMonday−Friday(919)677-8008E-mail:support@sas.com−reportproblemssuggest@sas.com−softwaresuggestionsWeb:support.sas.com/techsup/15DocumentationDocumentingSAS:¢ReferenceGuides¢GettingStartedGuides¢User’sGuides¢OperatingEnvironmentCompanionGuides¢ChangesandEnhancementsCurrentproductsandservices:¢PublicationsCatalog¢SASPress¢OnlineDocumentation16 9-10Chapter9LearningMoreDocumentationReferenceguides:¢SASonlinedocumentation¢DeliveredonaCD-ROM¢Shippedfreewithsoftware¢Singlecopiesavailable¢Hard-copybookstopurchasesupport.sas.com/documentation17SASPublishingsupport.sas.com/publishing18 9.2SASResources9-11UserGroupsBenefits:¢EnhanceyourunderstandingofSASsoftwareandservices.¢Exchangeideasaboutusingyoursoftwareandhardwaremostproductively.¢LearnofnewSASproductsandservicesassoonastheybecomeavailable.¢HavemoreinfluenceoverthedirectionofSASsoftwareandservices.19InternationalUsersGroupsSASGlobalForum(formerlySUGI)AnnualconferenceheldMarchorAprilinNorthAmericaSASForumInternational(formerlySEUGI)AnnualconferenceheldMayorJuneinEuropeSUGA(SASUsersGroupofAustralia)AnnualConferenceheldAugustorSeptemberinAustralia20 9-12Chapter9LearningMoreRegionalUserGroupsSESUGSoutheasternUnitedStatesNESUGNortheasternUnitedStatesMWSUGMidwesternUnitedStatesSCSUGSouth-CentralUnitedStatesWUSSWesternUnitedStatesRegionalconferencesareusuallyheldinSeptemberorOctober.21OtherUsersGroupsLocalCityorareausergroup.Oftenholdmultiplemeetingsperyear.SpecialInterestIndustry-specificusergroups.In-houseSingleorganizationorcompanyusergroup.WorldwideMostcountrieshavetheirownusersgroups.support.sas.com/usergroups22 9.2SASResources9-13NewsgroupsThereisanewsgroupnamedcomp.soft-sys.sas.Thisisabulletinboardforuserstopostquestions,answers,anddiscussSASsoftware.Toviewthisnewsgroup,useanynewsgroupviewer,suchasgroups.google.com.23NewsgroupsThenewsgroupisalsogatedtoalistserv.Tosubscribetothelistserv,sende-mailtoanyofthemailservers:¢listserv@listserv.uga.eduUniversityofGeorgia¢listserv@vm.marist.eduMaristUniversity¢listserv@listserv.vt.eduVirginiaPolytechnicUniversity¢listserv@AKH-WIEN.AC.ATUniversityofViennaThesubjectlineisignoredandthebodyshouldcontainthecommand:subscribesas-lyourname.Forexample,subscribesas-lTomSmithishowTomSmithwouldsubscribe.24 9-14Chapter9LearningMoreAdditionalInformationAccesstheSASWebsiteatwww.sas.comtolearnmoreaboutavailablesoftware,support,andservicesandtotakeadvantageoftheseofferings.25Wrap-UpDonotforgettodothefollowing:¢filloutyourevaluation¢deposityournamebadgeinthecontainerprovidedbyyourcoursecoordinator¢pickupyourdiploma26 9.2SASResources9-15ThankyouforattendingSAS®ProgrammingII:ManipulatingDatawiththeDATAStep.27 9-16Chapter9LearningMore AppendixAIndexaccumulatingtotalsforgroups,3-18–3-36$nonstandard,4-7sorting,3-18–3-20$w.informat,1-16standard,4-6DATAstatement,1-67__NULL_keyword,2-49_N_automaticvariable,2-55creatingmultipleSASdatasets,2-21_NULL_keywordDATAstepDATAstatement,2-49accumulatingtotalsforagroupofdata,3-17–3-36Acreatingaccumulatingtotalvariables,3-arrayprocessing,7-37–7-48,7-52–7-703–3-15ARRAYstatement,7-42–7-43explicitoutput,2-5–2-16syntax,7-42INFILEstatement,1-16,1-67assignmentstatements,1-16INPUTstatement,1-16,1-67syntax,1-67OUTPUTstatement,2-5–2-16overview,1-3–1-7Bprocessing,1-20–1-33PUTLOGstatement,6-9BYstatementreadingdelimitedrawdatafiles,4-3–4-40MERGEstatement,8-7readingfromexternalfiles,2-49usingwithaSETstatement,3-21readinghierarchicalrawdatafiles,4-88–BY-groupprocessing,3-20–3-364-148BYvariables,3-21readingmultiplerecordsperobservation,multipleBYvariables,3-32–3-374-46–4-50SETstatement,1-54,1-67Cwritingtoexternalfiles,2-49–2-65CEILfunction,5-57DATEfunction,5-66colonformatmodifier,4-9DATE9.format,1-68PUTstatement,2-52DATE9.informat,1-16COMMAw.dformat,1-40,1-68DAYfunction,5-67concatenationoperators,5-22DD=option,2-55CONTENTSprocedure,1-35–1-37,1-68DDNAME=option,2-55convertingdataDEBUGoption,6-17–6-19automaticcharactertonumeric,5-70–5-commands,6-1994delimiteddatafilesautomaticnumerictocharacter,5-86–5-reading,4-3–4-4089DELIMITER=option,2-64characterdatestoSASdates,5-85delimitersexplicitcharactertonumeric,5-77,5-92specifying,4-21INPUTfunction,5-75–5-76,5-82specifyingalternate,2-64RENAME=datasetoption,5-80DLM=optionFILEstatement,2-64DINFILEstatement,4-21,4-42DOloops,7-3–7-34data A-2Indexconditionaliterativeprocessing,7-24–7-H29hierarchicalfilesDOUNTILstatement,7-24–7-29creatingoneobservationperdetailrecord,DOWHILEstatement,7-24–7-294-90–4-111explicitOUTPUTstatement,7-21–7-23creatingoneobservationperheadernested,7-30–7-34record,4-112–4-146overview,7-4processing,4-88–4-89performingrepetitivecalculations,7-11–7-22IDOstatementsiterative,7-6–7-9IF-THENELSEstatements,1-54,1-67DOUNTILstatement,7-24–7-29indexvariablessyntax,7-25iterativeDOstatements,7-6–7-8DOWHILEstatement,7-24–7-29INFILEstatement,1-16,1-67,2-49syntax,7-25DLM=option,4-21,4-42DOLLARw.dformat,1-40,1-68DSDoption,4-39–4-41,4-42DROPstatement,1-55,1-67MISSOVERoption,4-42DROP=datasetoptionPADoption,4-31inPROCsteps,2-43TRUNCOVERoption,4-31DSDoptioninformats,1-16,4-8INFILEstatement,4-39–4-41,4-42specifyinginanINPUTstatement,4-9INPUTfunction,5-71,5-75–5-76,5-82EINPUTstatement,1-15–1-16,1-67,2-49,5-71EXAMINEcommandcolonformatmodifier,4-9DEBUGoption,6-19doubletrailing@option,4-77–4-79EXPORTprocedure,2-48specifyinginformats,4-9externalfilesusingmultiple,4-47readingfrom,2-55,2-65insertingcharacters,5-10writingto,2-49–2-65INTfunction,5-58extractingcharacters,5-10,5-48–5-51iterativeDOstatements,7-6–7-9conditionalclauses,7-28FFILEstatement,2-49–2-50JDLM=option,2-64joiningtablesfilespecifications,2-50usingtheSQLprocedure,8-27–8-37FILE=option,2-55FILENAMEstatement,2-51KFILEREF=optionfilespecifications,2-55KEEPstatement,1-55,1-67First.variable,3-20–3-36KEEP=datasetoptionFIRSTOBS=datasetoption,2-40inPROCsteps,2-43inPROCsteps,2-43SETstatement,2-41LFIRSTOBS=systemoption,2-40Last.variable,3-20–3-36FLOORfunction,5-57LENGTHstatement,1-55–1-56,1-67,4-11–FORMATstatement,1-39–1-41,1-684-12formats,1-39–1-41,1-68LIBNAMEstatement,1-44–1-47,1-69formattedinput,1-16LISTWATCHcommandFSLISTprocedure,2-55DEBUGoption,6-19LOGspecification IndexA-3FILEstatement,2-50PROCPRINTstatementlogicerrors,6-6NOOBSoption,1-38LOWCASEfunction,5-48–5-51ProgramDataVector(PDV),1-20ProgramEditorlinenumbercommands,1-M74–1-75PUTfunction,5-71,5-90–5-92match-mergingSASdatasets,8-3–8-24PUTstatement,2-49–2-53,6-6–6-9MDYfunction,5-66colonformatmodifier,2-52MEANfunction,5-63PUTLOGstatement,6-9MERGEstatementBYstatement,8-7QMISSOVERoption,4-29–4-31INFILEstatement,4-42QTRfunction,5-67MMDDYY10.format,1-40,1-68QUITcommandmodifiedlistoutput,2-52DEBUGoption,6-19MONTHfunction,5-67RNrawdatafilesnameprefixlists,5-6hierarchical,4-88–4-148namerangelists,5-6missingdataatendofarow,4-23–4-30nestedDOloops,7-30–7-34missingdatarepresentedbyconsecutivenonstandarddata,4-7–4-9delimiters,4-32–4-40reading,4-7–4-9multiplerecordsperobservation,4-48–4-NOOBSoption50PROCPRINTstatement,1-38readingcomma-delimited,4-20–4-22numberedrangelists,5-6readingspace-delimited,4-3–4-20readingwithlistinput,4-3–4-40Oremovingtrailingblanks,5-23–5-25RENAME=datasetoption,5-80OBS=datasetoption,2-36–2-38RETAINstatement,4-113inPROCsteps,2-43rotatingSASdatasets,7-63–7-70SETstatement,2-41ROUNDfunction,5-56ODSCSVALLstatement,2-46–2-47,2-46–2-47SOFkeywordSASvariablelists,5-7SASarrays,7-37–7-48OUTPUTstatementcreatingvariables,7-52–7-61DATAstep,2-5–2-16overview,7-39–7-40specifyingmultipledatasets,2-22performingrepetitivecalculations,7-37–7-38,7-46–7-48Pperformingtablelookups,7-62rotatingaSASdataset,7-63–7-70PADoptionSASdatalibraries,1-44INFILEstatement,4-31SASdatasetsPDV,1-20accessing,1-47performingrepetitivecalculationscreatingfromrawdatafiles,1-13–1-35DOloops,7-11–7-22creatingmultiple,2-21SASarrays,7-37–7-38,7-46–7-48creatingpermanent,1-51–1-52PRINTprocedure,1-35–1-37,1-68creatingwithSASdata,1-53–1-65VARstatement,1-42,1-65,1-68match-merging,8-3–8-24PRINTspecificationpermanent,1-46–1-51FILEstatement,2-50reading,1-54 A-4IndexrotatingusingSASarrays,7-63–7-70OFkeyword,5-7specifyingmultipleinanOUTPUTSASvariablesstatement,2-22naming,1-12structure,1-10requiredattributes,1-10–1-12viewing,1-48–1-50SASwindowingenvironmentviewingdataportion,1-36–1-38onOS/390,1-74–1-75viewingdescriptorportion,1-35–1-37onUNIX,1-72–1-73writingtomultiple,2-20–2-23onWindows,1-70–1-72SASdatevaluesSELECTgroups,2-23convertingcharacterdates,5-85SETstatement,1-54,1-67creatingusingfunctions,5-66FIRSTOBS=datasetoption,2-41extractinginformationfrom,5-67OBS=datasetoption,2-41SASformats,1-39–1-41,1-68usingwithaBYstatement,3-21SASfunctionssimplejoinscategories,5-3performingusingtheSQLprocedure,8-CEIL,5-5727–8-37computingstatistics,5-60SORTprocedure,3-18–3-20,8-7DATE,5-66sortingdata,3-18–3-20DAY,5-67specialSASnamelists,5-6FLOOR,5-57SQLprocedureINPUT,5-71,5-75–5-76,5-82FROMclause,8-32INT,5-58performingsimplejoins,8-27–8-37LOWCASE,5-48–5-51SELECTclause,8-32MDY,5-66standarddataMEAN,5-63character,4-6MONTH,5-67numeric,4-6QTR,5-67STEPcommandROUND,5-56DEBUGoption,6-19SUBSTR,5-10,5-48–5-51SUBSTRfunction,5-10,5-48–5-51SUM,5-63syntaxerrors,6-6syntax,5-4TODAY,5-66TTRANWRD,5-46–5-47tablelookupsTRIM,5-23–5-25performingwithSASarrays,7-62truncation,5-55–5-59TITLEstatement,1-69UPCASE,5-43TODAYfunction,5-66WEEKDAY,5-67TRANWRDfunction,5-46–5-47YEAR,5-67TRIMfunction,5-23–5-25SASinformats,1-16truncationfunctions,5-55–5-59SASlogTRUNCOVERoptionwritinginformationto,6-6–6-9INFILEstatement,4-31SASprogramsediting,1-75Uincluding,1-74opening,1-71UPCASEfunction,5-43saving,1-71,1-73,1-75submitting,1-71,1-72,1-74VSAStablesVARstatementassigningaliases,8-37PRINTprocedure,1-42,1-65,1-67joining,8-27–8-37variablesSASvariablelists,5-7BY,3-20–3-36 IndexA-5creatingwithSASarrays,7-52–7-61WFirst.,3-20–3-36w.informat,1-16Last.,3-20–3-36WATCHcommandmultipleBY,3-32–3-36DEBUGoption,6-19naming,1-12WEEKDAYfunction,5-67requiredattributes,1-10–1-12WORKlibrary,1-46settinglengths,4-11–4-12YYEARfunction,5-67

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。
大家都在看
近期热门
关闭