50% found this document useful (2 votes)
1K views42 pages

Learning SAS by Example A Programmers Guide Answers

SAS by example

Uploaded by

bhanu_billa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
50% found this document useful (2 votes)
1K views42 pages

Learning SAS by Example A Programmers Guide Answers

SAS by example

Uploaded by

bhanu_billa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 42
558 Learning SAS by Example: A Programmer's Guide Chapter 1 Solutions 2 nunber) is 10 sass * Default length for numerics is 8 */ Chapter 2 Solutions ae Ren Cody 2006 © ‘Means and sums of Portfolio Variable: ion mean sum maxdeSolutions to Odd. Numbered Problems 589 = LeSAv + (R/E)tE#3 = 125; Chapter 3 Solutions ea fence) / 4; average = (english + History + Mach + ing of SCORES"; 323; daca company; infile 'c:\books\te: LastName sing \conpany po § Sal /+ optional statement format Salary dotlari0.; ng of COMPANY" of TESTDATAY360 Learning SAS by Example: A Programmer's Guide roo pring data-testdata noobe; 307; data cache; infile ‘¢:\books\learning\geccaching txt’ padi wiote: PAD not necessary but a good idea See Chapter 21 for a discuasion of this: imput GeoName $ 1-20 Bongdeg 21-22 Longin 23-28 ZatDeg 29-30 Eatmin 31-36; title tListing of CACHE roo print datascache noobs, +329; data cache; infile ‘c:\books\Learning\geccaching. txt’ pad; imput @1 GesName $20 21 Longdeg 2 223 tongmin 5 029 Lacdeg = 2 631 batmin 6.5 title "Listing of CACHES; proe print datacache noobs; sa-at; data employ infile 'c:\books\learning\employee.csv' dsd missover; srimote: missover 1s not needed but a good idea suncover will also work See Chapter 21 for an explanation of missover and truncover ingile opticne at ID $3. Name §20. Depars $8 DareHire mnddyyi0. Salary dollars. input TD Name Depart DaveHtire Salary format DateHire dates; title ‘Listing of EMPLOY"; proc print data-enploy noobs;Solutions to Odd-Numbered Problems 561 Chapter 4 Solutions Libname learn ‘e:\books\learning’; daca learn.pern, Enput ID: $3. Gender height Weight; bok : mmddyyio abel pop = ‘Dace of Bi Height = ‘Height in inches Weight = ‘Weight In pounds’; format BOB daced.; 001 @ 10/21/1946 68 002 F 5/26/1950 63 1. 003 m S/1i/ieai 72 2 aoe m 7/4/1983 70 128 905 F 12/25/2005 30 40 ‘contents of data set PERM" 1403 fname perm ‘e:\hooks\learning input Age Gender $ (Quesi-guess) ($1.); 23M 15243 30 F 11223 42 w 23555 4@ F 55541 55 F 42232 52 F 33333 68 m 44122 ‘*#topening up a new session, you need a Libnane atatemenc, ibname perm ‘22h aks \ earning ticle "Computing Average Age"? proc means data=perm. survey2007362 Learning SAS by Example: A Programmer's Guide Chapter 5 Solutions value §party 'D value $Likert ‘1 ‘Strongly Disagree! 2 3 5: = ‘strongly Agree nput Age Party : $1. (Quesi-gu ay ist. + Ds label Quest = * ing a good job Ques? ing a good job" Ques} = ‘taxes are too high Quesd = ‘Government should cut spending’; format age agegry. Party Sparty Quesi-Quesd Siikert.; 23 22 87 a a8 ‘ ° 2a 5 23 3 ae proc freq data=voter; tables Quesi-gues4;Solutions to Odd. Numbered Problems 563 15-3 nput Color : $1. 68 REGYY..2GRBGYPOOVVE value §color 'R','8','G! = ‘rou 1 Heitor = 'eroup 2" other = ‘Group 3" proc freq datascolors; tables color / nocum mij ‘color Frequencies (Grouped) * ng, ‘The MISSING option places the frequency of missing values in the body of the table and causes the percentages to be fornat color $color.; ibname learn ‘e;\books\learning’ ; options fmesearca= (learn) ; proc format Library=Learn’ fimtLib: value yesno 1='¥es' 2=!No'; value §yesno 'Y'="Yes" value fgender '"='Nale value age20y> 61-80 Select File --> import pata Choose Excel and select Srugtest.xla364 Learning SAS by Example: A Programmer's Guide a5 Db 3 achool, put Age Qu f age = 12 else If Age if quiz = "4 el ouiz Quiz else i2 Quiz 1 \books \learning\soccer x18 2: $1. mid then Grae = 13 then Gr then Quizs: = 'B! Shen c! then ise if Quiz = 'F! then Courgegrade = ,2*Quizcra 292 95 12 B 8 68 1c 7875 13 A 92 93 12 P55 62 a3 Bae 62 title “Listing of scwoon*; proc print data-school noob: “703 citle "selec! ple! "9888" or 5: uiz Quiz Quiz Quiz ees from SA EnpipSolutions to Odd-Numbered Problems 568 ength Cholsroup $ 6 zelect; when (missing (chol}} CholGroup = * +; when (Chol le i10) CholGroup = ‘Low’; when (Chol le 140) CholGreup = ‘Medium’; otherwise CholGro’ Higa! end, title *histing of BLOOD ‘loed noobs sitle ‘Selected cheervations from BICYCLES proc print data-learn. bicycles noobs where Model eq Road Bike" and Unircost gt 2500 or Model eq *Hybrid* and Unizcoat gt 650 ‘Wose: parentheses ave not needed since Che AND operation is performed before OR, You may include then if you wish; DEP, label SBP = ‘systolic Blood Pressure" DBP = ‘Diastolic Blood Pressure"; 120 80 eB 96 100 82 150 98 100 stenote: thia program assumes there are no missing values for >ulse or SRP;366 Learning SAS by Example: A Programmer's Guide daca newvitate; set vitals; LE Age 1 50 and nov missing (Age) then dor Lf Pulse le 70 then PulseGroup = ‘Low ' else Pulsetroup = 'High'; AE SBP le 140 then SBPGroup = ‘Low 'y else sapcroup = ‘High’: end: else iz Age ge 50 then do; Af Pulse lt 7 then ?ulsecroup = ‘Low’; else PulseGroup = ‘High'; Lf SBP le 140 then SBPGroup else SBPGroup = "High's end; "tow": title ‘histing of NEWWITALS* proc print datasnewvitals noobs +823; data test; input 8 Subj + 1) aacalines; 30 85 92 15 76 88 be 82 92 72 68 70 wel-Scored title tListing of TEST? roe print data-tes= noche; +825; data logs: doN = 1 to 20; Log = Logit) output; end; title “Listing of toss" proc print data-logs nosh; see7; data plotit do x= 0 to 10 by 1Solutions to Odd. Numbered Problems 567 y = 31xt+2 - 54x + 10 output; ena; goptions symbol proc gplot datasplotit; plot y * x: quit +829; data temperatures; do Day = 'Mon', 'Pues*, "Wed", ‘Thu’, "Frit, ‘Sat", 'Sun'; input Tem @; output; end; aacalines; 70.72:16 76:17:78 8S title “Listing of TEMPERATURES"; proc print datastemperatures noobs; seea; data temperature: Tength city $75 do City = "Dallas*, ‘Houston’ Go Hour = 1 to 24; input Temp @; datalines; 80 61 82 83 64 84 87 88 69 89 91 93 93 95 96 97 99 95 92 90 88 85 84 80 78 76:77:78 80 &1 42 62 86 88 90 92 $2 93 96 94 92 90 ee 86 82 78 76 74368 Learning SAS by Example: A Programmer's Guide ves in allag and Hous! 1 to 999 until (Amount ge 30000! 900 + Amount * (0425/4); ng of Mowey™ 33 madyyo daves.; age = yrait (Dos, visit, ‘Actual }; format DOR Vieit dazed 90110/21/185011Nev2008, 00202 /02/198825May2005, 00322/25/200825ec2006 92/23/05Solutions to Odd. Numbered Problems 569 03/25/15 95/09/06 options year /* Good idea to set yearcutof! back to the default after you change it */ title ‘Listing of YEARIS10_2006"; proc print datasyear1910_2006 nooks 19-5; data Srea: ‘set learn. hosp (keep=AdnitDate) ; Day = weekday (AdnitDate) ; Month = month (AdnitDate) Year = year (AdmicDace} ; proc format value days 1 “Tue! ‘Sep es for Hospital Admissions"; req: tables Day wonth Year / nocum nopercent, format Day days. Monta months. +909; title "Adrissions before suly 15, 2002" proc print dataslearn.hosp; where AdmitDate le '01sul2002'a and AcricDate is not missing 19-9; data daces; input Day Month Year; Af missing(Day) then 3: dy (Month, 15, Year) ; else Date = mdy (Month, Day, Year}; format Date mnddyy10. datalines; 25 12 2005 5 2002510 Learning SAS by Example: A Programmer's Guide fe “Lia! sof DATES"; proc print data=dates nocks Quarters = intek('a Jan2006"A,VisivDace) ; proc print data-return noobs Chapter 10 Solutions waere Gender eq Combined = .001*WEC + REC: male‘ and Blocdtype='Az! title "Listing of suasi proc print data=subset_a noobs ooltwac + Re; ‘Peale! and Blocdtyp Ag! and Combined ge 2Solutions to Odd-Numbered Problems S71 ticle "Listing of susser_er proc print data=subset_» noobs; 10-3; data lowale lowfenale; set learn.blood; waere Chol 1¢ 100 and Chol ia not missing J+ alternative statenent Where Chol 1t 160 and not missing {chol) if Gender = ‘Female’ chen output lowfemale; else if Gender = ‘Male’ then ouput lownale; title thisting of LONMALE; proe print data=lowmale noobs; title "Listing of LONFEMALE*; proc print data-lowfenale necks) 10-5; title *histing of Tivewroay:; proc print data=learn. inventory noobs; title "Listing of NEWPRODUCTS*; proe print data-leara.newprod daca updated; set learn. inventory learn nesproducts; title thisting of updazea"; proe print data-updated,572 Learning SAS by Example: A Programmer's Guide 10-7; prog means data=learn.gym noprint; var fee; output outsMeanfee(drop=_type_ _freq_) Mean-Avefee; gata percent: get learn. gym Af n= 1 then set Meanfee; FeePercent = round(100*fee / avetee) arop Avefee; title tListing of PERCEND* pros print data-PERCENT, 10-9; proc sort dat. by Nodels ry outsinventory; proc sort data-learn.purchase out-purchase; by Model! by Model! if Inpurchase; potalprice = Quantity*?rice; format Totalprice dollar8.2; title “Listing of PURLPRICE*; proc print data-pur_price necks; “10-11; options mergenoby=nowarn: gata try; merge learn. inventory Learn.purchase: title "Listing of TRYIt roe print dataceyl;options mergenohs data try2; Solutions to Odd. Numbered Problems 873 merge learn. inventory learn.purchase, title ‘Listing of TaY2 proc print Gata-tey2; options mergenobyserror; data try; rerge Learn. inventory Learn.perchaser title ‘Listing of TY3" proc print data-teyé s10-13; /* Solution where the numeric identifier is converted daca survey?; set learn. survey (rename=(1D 3D = put (NumID, 23.}; Grop NumID; proc sort data-survey2; by ID data combine: nerge demographic survey2; by ID; title thisting of cosine; proe print data=conbine noobs; /* Solution wheze the chazacter to a numeric value */ gata demographic: set learn. denograzhic (rename MunD) ): identifier is converted (ap = cnarz));574 Learning SAS by Example: A Programmer's Guide jchar19,3.) by ID: datasdenographic; proc sort data-learn.survey2 out-survey? by TD merge demographic survey2; title "Listing of CoMBINE™; Chapter 11 Solutions (ieight* 0254) +62, BurRownd = round (3M2) ; BEERound, fenth = round(BMZ, .1); round (2MI,5) ; bleed; = missing (WBC) then call missing(Gender,28¢, Chol)Solutions to Odd. Numbered Problems 578 title thisting of Mrss_sioop:; proe print data=miss bleed noobs; suns; data psychscore; ‘set learn.psych: Scorehve = mean (largest (1,0f Scorel-scorss) , largest (2,0f Scorel-scores}, largest (3, 0f Scoel-scores) } Af n(of Quesi-guesid) ge 7 then QuesAve = mean(of Quesi-guesi0) ; Composit = ScoreAve + 10*Quesave; keep ID ScoreAve QuesAve Composit; title thisting of esycHscoRE:; proc print dataspsychscore noobs; sist; data pull; x 510) y = 20) 2 = -30; Abs2 = abs(z): ExpX = round (exp (x) , 001); Circumference = round (2*constant ("pi") *y, 001); pat calls s11- data fake; do Subj = 1 to 100, Af ranuni (12345) le .4 then Gender = ‘Fenale’; glee Gender = Male Age = int (ranuni(12345)#50 + 10) output; ena; title “First 10 observations of FAKE"; proc print data-fake (obs=10) ; saan daca convert get learn. char_num(rename=576 Learning SAS by Example: A Programmer's Guide (age = chax_Age Weight = Char_Weight Zip = Num zip SS = Nonss)); Age = input (Char_age, 8.) ght = input (Char_Age,6.)7 (gun_ss, ssn]1) Zip = put (ium Zip,25-); le "Listing of CONCERT"; ea fh Pricel = lag (Pri Price2 = lag2(Pr average = mean(Price, Pricel, Price2); goptions reset-ail colors: symbol vedot Lines izsnooth; symbol? vesquare line=2 i=amo0 title "Plot of Price and Moving Average" proc gplot data-anooth; Average*Date / overlay; Chapter 12 Solutions 12-1; tone way to test the storage lengths is to use the LENGTH function chat returns storage lengths \e LENGTH function that returns © cer string, length AS 42 4;Solutions to Odd. Numbered Problems 877 cat = cate(a.s); Af Mame = 'Shith’ then Mateh = 'No'; else Match = "Yes"; Substring = substr (Name, 5,2); TA = Lengthe(al: EB = Lenethe(s) Name = lengthe (Name) ; LAands = lengthe(aands} cat = lengtac (cat) Match = Lengthe (Match) LSubstring = Lengthe (Substring) title ‘Lengths of Character Variables"; roe print data-storage noobs; var Lt ‘ALL Variables starting with LL; Variable Storage Length A 4 2 4 Name ° and, 8 cat 200 match 2 Substring 3 12-3; daca nanes_and nove, ‘get learn names_and more, Nane = comp! (ame) 7 Phone = compress (Phone, , kd") citle “Listing of Data Set LEARN.NAMES_AND_MORE*; proc print data-nanes_and.moze noobs; 12-5; data convert; set learn.names_and_pore (keep=Mixed) Integer = Input (scan (Mixed,1," /*),8.); Numerator = input (scan (Mixed,2," /"), 8.) Denominater = input (scan (Mixed,3," /*),8.); if missing{unerator) then Price = Integer; glee Price = Integer + Sumeracor / Denominacor; Grop Numerator Denominator integer;578 Learning SAS by Example: A Programmer's Guide title "Listing of CONVERT"; proc print date=convert noobs; 12-7; ‘Using one of gata concat set learn, length Combined $3; Combined = catx(*~', Group, Subgroup) ; title ‘Listing of coNcAn; roe print data-concat noobs; swithout using CAT functions; data concat set learn, study (keep=Group Subgroup) Length Combined $3; Combined = trim(Grous) || '-* || put (Subgroup, 1.9; title thisting of coNcAD*; prot print data=coneat noobs; 12-9; data spirited; get learn. gales, waere find (Customer, piste! i): title "Listing of SPIRITED" proc print data=spirited noobs; saa-21 sitle ‘Subjects from SRRORS with Digits in the Name'; proc print datasleara.errors nocks; where anydigit (vane) var Subj Name; 12-13; daca exact withings get learn. eccial, AE SSI eg $82 then output exact; else if spedis(ssi,ss2) le 25 andSolutions to Odd. Numbered Problems 579 not missing(Ssi) and not migsing(Ss2) then out withinas;| sting of wxTHrwas* | nore (kee fengch AreaCode $ 27 hreacode = substy (Phone,2,3) ng of NUMBERS" 004 get learn personal (deo: substr(85,1,7) subscr (Ace title "Listing of PERSONAL {with masked values)"; int data=personal nochs, Chapter 13 Solutions sa3-1; array Ques(5) $ Q1-05; do i= ito 5 @ slate (ou! 54322 » end,5380 Learning SAS by Example: A Programmer's Guide title ‘hist of SURVEYL (rescaled) "; proe print data=surveyl s13-3; data nonines: ‘set learn-nines: array nuna(*) numeric; Go i= 1 to ain(numa) Af mums(i) = 992 then call missing (nums(i)) ena; drop iy title thisting of NONINES"; proc print datasnonines: +1325; data passing: array pass_score(5) _temporary_ (55,70, 80, 52,68) array Score(S); imput ID: $3. 8: NunberPassed = 0; do Test = 1 te 5 NurberPassed + (Score(Test) ge pass. ena; Grop Test; Gatalines; o01 90 88 92 95 90 002 64 66. 77:72: 72 003 68 59 80.75 70 008 88 77-5 77 67 ssorel-seores title “Listing of PASSING"; proc print data=passing: id ipsSolutions to Odd. Numbered Problems 581 Chapter 14 Solutions Chapter 15 Solutions “1 title "Tirst 5 Observacions from Bleed Data sec? proc report data=learn.blood{obs=5} nowa headline; column Subject WBC RBC; define Subject / display “subject Number* width=7; WBC / ‘White Blood Celle" widen=¢ format=connas.0 REC / "Rea Blood Cella mate5.2;5382 Learning SAS by Example: A Programmer's Guide 15-3; title "Denonstrating a Compute Block"; proc report data-learn.hosp (obs=5) now headline; column Subject AdmicDate DOB Age; define AdnitDate / display *Adnission Date" width=10; Gedine boz / display; Gefine Subject / diaplay wide! Gefine Age / computed “Age at Adnigaion" ; compute Age; Age = round (yrdif(D0B, AdnicDate, 'Actual'}); endconp; quit: 15-5; title tpatient age Groups! proc report data-learn. bloodpressure nowd; colunn Gender Age AgeGroup; Gefine Gender 7 width=s. define Age / display wide! define AgeGroup / computed "Age Group"; compute AgeGroup / character lengt! AE Age gt 50 chen AgeGroup = "> 50"; else if not missing(Age) chen AgeGroup = endeomp; uit: s1s-7; title "Mean Cholesterol by Gender and Blood Type"; proc report data=learn.blood nowd headline ‘column Blood?ype Chol: Serine 7 group wide! Gefine Bloodtype / group "Blood Type" width=5 define Chol / analysis mean "Kean cholesterol" width=11 format quit: s18-9; sitle ‘Report on the suvey Data sett; proc report data-Tearn.aurvey nowd headline column 1D Age Gender Salary Quesi-quess AveResponse; define 1D / display width=4; define Age / display wide! Gefine Gender / display wide! define Salary / display widch-10 format-dollario.; Gefine Quesl / display noprinc;Solutions to Odd-Numbered Problems 583 gues2 define Ques’ Gefine Quesé / display nopri gue: / display noprint; ‘Tals solution will cause an automatic AveResponse = mean(of Quesi-guesS) endeomp; To avoid the automatic tne code below £ che aveResponse ft (guesl nput (Ques? , put (Ques3 /1.)7 nput (Ques’,1.) 7 = input (Quess/1.); AveResponse = mean(of 1-95) endcorp: define AveResponse / com sd "Average Response" wi Chapter 16 Solutions s16-1;584 Learning SAS by Example: A Programmer's Guide var ClasaRank GPA, 16-3; proc sort data-learn.college out-college; by Schoolsize: title "statistics on the college bata set - Using BY"; citle2 "Broken down by School Size* proc means datascollese median maxde by Schoolsize; var ClassRank GPA;run; title “Statistics on the College Data set ~ Using CLASS"; title? “Broken down by School Size"; proc means data-learn. college median min class 5: var ClassRank GPA; “16-5; proc format value rank 0-50 = ‘Bottom Half! S174 = ‘Third quartiles 75-100 = ‘Top Quarter"; sitle ‘Statistica on the College bata set"; titie2 *Broken down by School Size* proc means data=learn.college class Clasexank var GPA? format ClageRank rank. ;Solutions to Odd-Numbered Problems 588 v6 proc mean data-learn.college noprint chartype: class Gender Schoolsize; var ClassRank GPA; at outesunmary grand (drop= size) bygender (arop=Schoo1size) byaize (drop=sende GRAND"; datasgrand nooks bygender noobs; ag of BI TZE* datashysize noobs; Chapter 17 Solutions title "One-way Prequencie: roe freq dat ‘a.blood, tables Gender Blocdlype AgeGroup / nocum nopercent;586 Learning SAS by Example: A Programmer's Guide e2 "Wi proc freq da tables title "Demonstrating the MISSING option*; 22 ‘With MISSING Option" oc freq dataslearn blood; tables Chel / nocun missing; format Chol cholaxp va7-5; value rank Lo ow to 70 “high = ‘71 and higher format ClagsRane sare; title "Blood Types in Decreasing Frequency order" proc freq datalearn.blood order=trea: tables Bloodtype / nocum nopercent; Chapter 18 Solutions s1a-1; options fm earn) ; fe "Demographics from COLLEGE Data set"; tabulate datanle ‘lege format=5.; lass Gender Scholarship Schoolsize; tables Genders: allSolutions to Odd. Numbered Problems 587 keylabel ne! '; 18-3; proc format; value {gender 'F* = ‘Fenale’ we = oMale’; title "Denographics from COLLEGE Data set"; proc tabulate datazlearn.college forma class Gender Scholarship SchoolSize; tables (Gender all) (Scholarship all), Schoolsize all / =ts=25; keylabel nz! ALL = ‘focal’ format Gender ¢gence 18-5; title "Descriptive stavistics*; proc tabulate datazlearn.college fozmat=6.1; class Gender; var GPA, fables GPAt (ats 20° ice gt 20; create table nsales a select Name, Totalsales from Lear waere Region eq ‘North’ Weight r.Sub! as Rightsubl,598 Learning SAS by Example: A Programmer's Guide title thisting of BOTH proe print datasboth noobs; /* alternate code proe eal; creace cable hoch as select 1.Subj as Lectsubj Height Weight r.Subj as Rightsubj, salary from learn. left as 1, learn right as = waere left Subj = right subj eit title *histing of BOTH prot print data=both noobs; werpare 2) proc eal; creace table Hoth as select 1-Sub! as Leftsubj Height Weight = .Sub! as Rightsuhi, salary from learn.left az 1 full join Learn right as on left Subj = righ quit title “Listing of BoTHt proc print datasboth noobs; veepare 3; roe eal create table both as select 1.Subj as Leftsubj Height Weight, r.Subj as Rightsubj, salary from learn. left as 1 left joinSolutions to Odd. Numbered Problems 599 learn.right as = on Left.Subj = right. subj; uit: title "Listing of LEFT proc print datasboth necks; 126-7; proe sal; create table third a select * from learn, first union all corresponding Select * from learn. second; eit title ‘Listing of THIRD"; proc print data-third; *26-9; proc eal; create Cable percentages as gelect Subject, RBC, pc, mean (RBC) as Meankec, mean(WBC) as MeaniEC, 100*REC / calculated Meank#C as Percent_Ruc, Losec / calculated Meanh2C az 2ercent wae from learn.blsed(obs=10) quit title "Listing of PERCENTAGES"; proc print dataspercentages

You might also like