reilly media] r cookbook navigating the software

reilly media] r cookbook navigating the software

ID:7323467

大小:374.53 KB

页数:20页

时间:2018-02-11

上传者:U-5649
reilly media] r cookbook navigating the software_第1页
reilly media] r cookbook navigating the software_第2页
reilly media] r cookbook navigating the software_第3页
reilly media] r cookbook navigating the software_第4页
reilly media] r cookbook navigating the software_第5页
资源描述:

《reilly media] r cookbook navigating the software》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库

CHAPTER3NavigatingtheSoftwareIntroductionRisabigchunkofsoftware,firstandforemost.Youwillinevitablyspendtimedoingwhatonedoeswithanybigpieceofsoftware:configuringit,customizingit,updatingit,andfittingitintoyourcomputingenvironment.Thischapterwillhelpyouperformthosetasks.Thereisnothinghereaboutnumerics,statistics,orgraphics.ThisisallaboutdealingwithRassoftware.3.1GettingandSettingtheWorkingDirectoryProblemYouwanttochangeyourworkingdirectory.Oryoujustwanttoknowwhatitis.SolutionCommandlineUsegetwdtoreporttheworkingdirectory,andusesetwdtochangeit:>getwd()[1]"/home/paul/research">setwd("Bayes")>getwd()[1]"/home/paul/research/Bayes"WindowsFromthemainmenu,selectFile→Changedir....OSXFromthemainmenu,selectMisc→ChangeWorkingDirectory.ForbothWindowsandOSX,themenuselectionopensthecurrentworkingdirectoryinafilebrowser.Fromthere,youcannavigatetoanewworkingdirectoryifdesired.51 DiscussionYourworkingdirectoryisimportantbecauseitisthedefaultlocationforallfileinputandoutput—includingreadingandwritingdatafiles,openingandsavingscriptfiles,andsavingyourworkspaceimage.Whenyouopenafileanddonotspecifyanabsolutepath,Rwillassumethatthefileisinyourworkingdirectory.TheinitialworkingdirectorydependsuponhowyoustartedR.SeeRecipe1.2.SeeAlsoSeeRecipe4.5fordealingwithfilenamesinWindows.3.2SavingYourWorkspaceProblemYouwanttosaveyourworkspacewithoutexitingfromR.SolutionCallthesave.imagefunction:>save.image()DiscussionYourworkspaceholdsyourRvariablesandfunctions,anditiscreatedwhenRstarts.Theworkspaceisheldinyourcomputer’smainmemoryandlastsuntilyouexitfromR,atwhichtimeyoucansaveit.However,youmaywanttosaveyourworkspacewithoutexitingR.Youmightgotolunch,forexample,andwanttoprotectyourworkagainstanunexpectedpoweroutageormachinecrash.Usethesave.imagefunction.Theworkspaceiswrittentoafilecalled.RDataintheworkingdirectory.WhenRstarts,itlooksforthatfileand,iffound,initializestheworkspacefromit.Asadfactisthattheworkspacedoesnotincludeyouropengraphs:thatcoolgraphonyourscreendisappearswhenyouexitR,andthereisnosimplewaytosaveandrestoreit.Sobeforeyouexit,savethedataandtheRcodethatwillre-createyourgraphs.SeeAlsoSeeRecipe1.2forhowtosaveyourworkspacewhenexitingRandRecipe3.1forsettingtheworkingdirectory.52|Chapter3:NavigatingtheSoftware 3.3ViewingYourCommandHistoryProblemYouwanttoseeyourrecentsequenceofcommands.SolutionScrollbackwardbypressingtheuparroworCtrl-P.Orusethehistoryfunctiontoviewyourmostrecentinput:>history()DiscussionThehistoryfunctionwilldisplayyourmostrecentcommands.Bydefaultitshowsthemostrecent25lines,butyoucanrequestmore:>history(100)#Show100mostrecentlinesofhistory>history(Inf)#ShowentiresavedhistoryForveryrecentcommands,simplyscrollbackwardthroughyourinputusingthecommand-lineeditingfeature:pressingeithertheuparroworCtrl-Pwillcauseyourprevioustypingtoreappear,onelineatatime.Ifyou’veexitedfromRthenyoucanstillseeyourcommandhistory.Itsavesthehistoryinafilecalled.Rhistoryintheworkingdirectory,ifrequested.Openthefilewithatexteditorandthenscrolltothebottom;youwillseeyourmostrecenttyping.3.4SavingtheResultofthePreviousCommandProblemYoutypedanexpressionintoRthatcalculatedthevalue,butyouforgottosavetheresultinavariable.SolutionAspecialvariablecalled.Last.valuesavesthevalueofthemostrecentlyevaluatedexpression.Saveittoavariablebeforeyoutypeanythingelse.DiscussionItisfrustratingtotypealongexpressionorcallalong-runningfunctionbutthenforgettosavetheresult.Fortunately,youneedn’tretypetheexpressionnorinvokethefunc-tionagain—theresultwassavedinthe.Last.valuevariable:3.4SavingtheResultofthePreviousCommand|53 >aVeryLongRunningFunction()#Oops!Forgottosavetheresult![1]147.6549>x<-.Last.value#Capturetheresultnow>x[1]147.6549Awordofcaution:thecontentsof.Last.valueareoverwritteneverytimeyoutypeanotherexpression,socapturethevalueimmediately.Ifyoudon’trememberuntilanotherexpressionhasbeenevaluated,it’stoolate.SeeAlsoSeeRecipe3.3torecallyourcommandhistory.3.5DisplayingtheSearchPathProblemYouwanttoseethelistofpackagescurrentlyloadedintoR.SolutionUsethesearchfunctionwithnoarguments:>search()DiscussionThesearchpathisalistofpackagesthatarecurrentlyloadedintomemoryandavailableforuse.Althoughmanypackagesmaybeinstalledonyourcomputer,onlyafewofthemareactuallyloadedintotheRinterpreteratanygivenmoment.Youmightbewonderingwhichpackagesareloadedrightnow.Withnoarguments,thesearchfunctionreturnsthelistofloadedpackages.Itproducesanoutputlikethis:>search()[1]".GlobalEnv""package:stats""package:graphics"[4]"package:grDevices""package:utils""package:datasets"[7]"package:methods""Autoloads""package:base"Yourmachinemayreturnadifferentresult,dependingonwhat’sinstalledthere.Thereturnvalueofsearchisavectorofstrings.Thefirststringis".GlobalEnv",whichreferstoyourworkspace.Moststringshavetheform"package:packagename",whichindicatesthatthepackagecalledpackagenameiscurrentlyloadedintoR.Inthisexample,theloadedpackagesincludestats,graphics,grDevices,utils,andsoforth.Rusesthesearchpathtofindfunctions.Whenyoutypeafunctionname,Rsearchesthepath—intheordershown—untilitfindsthefunctioninaloadedpackage.Ifthefunctionisfound,Rexecutesit.Otherwise,itprintsanerrormessageandstops.(There54|Chapter3:NavigatingtheSoftware isactuallyabitmoretoit:thesearchpathcancontainenvironments,notjustpackages,andthesearchalgorithmisdifferentwheninitiatedbyanobjectwithinapackage;seetheRLanguageDefinitionfordetails.)Sinceyourworkspace(.GlobalEnv)isfirstinthelist,Rlooksforfunctionsinyourworkspacebeforesearchinganypackages.Ifyourworkspaceandapackagebothcon-tainafunctionwiththesamename,yourworkspacewill“mask”thefunction;thismeansthatRstopssearchingafteritfindsyourfunctionandsoneverseesthepackagefunction.Thisisablessingifyouwanttooverridethepackagefunction...andacurseifyoustillwantaccesstothepackagefunction.RalsousesthesearchpathtofindRdatasets(notfiles)viaasimilarprocedure.Unixusers:don’tconfusetheRsearchpathwiththeUnixsearchpath(thePATHenvi-ronmentvariable).Theyareconceptuallysimilarbuttwodistinctthings.TheRsearchpathisinternaltoRandisusedbyRonlytolocatefunctionsanddatasets,whereastheUnixsearchpathisusedbyUnixtolocateexecutableprograms.SeeAlsoSeeRecipe3.6forloadingpackagesintoR,Recipe3.8forthelistofinstalledpackages(notjustloadedpackages),andRecipe5.31forinsertingdataframesintothesearchpath.3.6AccessingtheFunctionsinaPackageProblemApackageinstalledonyourcomputeriseitherastandardpackageorapackagedown-loadedbyyou.Whenyoutryusingfunctionsinthepackage,however,Rcannotfindthem.SolutionUseeitherthelibraryfunctionortherequirefunctiontoloadthepackageintoR:>library(packagename)DiscussionRcomeswithseveralstandardpackages,butnotallofthemareautomaticallyloadedwhenyoustartR.Likewise,youcandownloadandinstallmanyusefulpackagesfromCRAN,buttheyarenotautomaticallyloadedwhenyourunR.TheMASSpackagecomesstandardwithR,forexample,butyoucouldgetthismessagewhenusingtheldafunc-tioninthatpackage:>lda(x)Error:couldnotfindfunction"lda"3.6AccessingtheFunctionsinaPackage|55 Riscomplainingthatitcannotfindtheldafunctionamongthepackagescurrentlyloadedintomemory.Whenyouusethelibraryfunctionortherequirefunction,Rloadsthepackageintomemoryanditscontentsbecomeimmediatelyavailabletoyou:>lda(f~x+y)Error:couldnotfindfunction"lda">library(MASS)#LoadtheMASSlibraryintomemory>lda(f~x+y)#NowRcanfindthefunctionCall:lda(f~x+y)Priorprobabilitiesofgroups:..(etc.).Beforecallinglibrary,Rdoesnotrecognizethefunctionname.Afterward,thepackagecontentsareavailableandcallingtheldafunctionworks.Noticethatyouneedn’tenclosethepackagenameinquotes.Therequirefunctionisnearlyidenticaltolibrary.Ithastwofeaturesthatareusefulforwritingscripts.ItreturnsTRUEifthepackagewassuccessfullyloadedandFALSEotherwise.Italsogeneratesamerewarningiftheloadfails—unlikelibrary,whichgeneratesanerror.Bothfunctionshaveakeyfeature:theydonotreloadpackagesthatarealreadyloaded,socallingtwiceforthesamepackageisharmless.Thisisespeciallyniceforwritingscripts.Thescriptcanloadneededpackageswhileknowingthatloadedpackageswillnotbereloaded.Thedetachfunctionwillunloadapackagethatiscurrentlyloaded:>detach(package:MASS)Observethatthepackagenamemustbequalified,asinpackage:MASS.Onereasontounloadapackageisthatitcontainsafunctionwhosenameconflictswithasame-namedfunctionloweronthesearchlist.Whensuchaconflictoccurs,wesaythehigherfunctionmasksthelowerfunction.Younolonger“see”thelowerfunc-tionbecauseRstopssearchingwhenitfindsthehigherfunction.Henceunloadingthehigherpackageunmasksthelowername.SeeAlsoSeeRecipe3.5.56|Chapter3:NavigatingtheSoftware 3.7AccessingBuilt-inDatasetsProblemYouwanttouseoneofR’sbuilt-indatasets.SolutionThestandarddatasetsdistributedwithRarealreadyavailabletoyou,sincethedatasetspackageisinyoursearchpath.Toaccessdatasetsinotherpackages,usethedatafunctionwhilegivingthedatasetnameandpackagename:>data(dsname,package="pkgname")DiscussionRcomeswithmanybuilt-indatasets.ThesedatasetsareusefulwhenyouarelearningaboutR,sincetheyprovidedatawithwhichtoexperiment.Manydatasetsarekeptinapackagecalled(naturallyenough)datasets,whichisdis-tributedwithR.Thatpackageisinyoursearchpath,soyouhaveinstantaccesstoitscontents.Forexample,youcanusethebuilt-indatasetcalledpressure:>head(pressure)temperaturepressure100.00022200.00123400.00604600.03005800.090061000.2700Ifyouwanttoknowmoreaboutpressure,usethehelpfunctiontolearnaboutitandotherdatasets:>help(pressure)#BringuphelppageforpressuredatasetYoucanseeatableofcontentsfordatasetsbycallingthedatafunctionwithnoarguments:>data()#BringupalistofdatasetsAnyRpackagecanelecttoincludedatasetsthatsupplementthosesuppliedindatasets.TheMASSpackage,forexample,includesmanyinterestingdatasets.Usethedatafunctiontoaccessadatasetinaspecificpackagebyusingthepackageargument.MASSincludesadatasetcalledCars93,whichyoucanaccessinthisway:>data(Cars93,package="MASS")Afterthiscalltodata,theCars93datasetisavailabletoyou;thenyoucanexecutesummary(Cars93),head(Cars93),andsoforth.3.7AccessingBuilt-inDatasets|57 Whenattachingapackagetoyoursearchlist(e.g.,vialibrary(MASS)),youdon’tneedtocalldata.Itsdatasetsbecomeavailableautomaticallywhenyouattachit.YoucanseealistofavailabledatasetsinMASS,oranyotherpackage,byusingthedatafunctionwithapackageargumentandnodatasetname:>data(package="pkgname")SeeAlsoSeeRecipe3.5formoreaboutthesearchpathandRecipe3.6formoreaboutpackagesandthelibraryfunction.3.8ViewingtheListofInstalledPackagesProblemYouwanttoknowwhatpackagesareinstalledonyourmachine.SolutionUsethelibraryfunctionwithnoargumentsforabasiclist.Useinstalled.packagestoseemoredetailedinformationaboutthepackages.DiscussionThelibraryfunctionwithnoargumentsprintsalistofinstalledpackages.Thelistcanbequitelong.OnaLinuxcomputer,thesemightbethefirstfewlinesofoutput:>library()Packagesinlibrary'/usr/local/lib/R/site-library':bootBootstrapR(S-Plus)Functions(Canty)CGIwithRCGIProgramminginRclassFunctionsforClassificationclusterClusterAnalysisExtendedRousseeuwetal.DBIRDatabaseInterfaceexpsmoothDatasetsfor"Forecastingwithexponentialsmoothing"..(etc.).OnWindowsandOSX,thelistisdisplayedinapop-upwindow.Youcangetmoredetailsviatheinstalled.packagesfunction,whichreturnsamatrixofinformationregardingthepackagesonyourmachine.Eachmatrixrowcorrespondstooneinstalledpackage.Thecolumnscontaintheinformationsuchaspackagename,librarypath,andversion.TheinformationistakenfromR’sinternaldatabaseofin-stalledpackages.58|Chapter3:NavigatingtheSoftware Toextractusefulinformationfromthismatrix,usenormalindexingmethods.ThisWindowssnippetcallsinstalled.packagesandextractsboththePackageandVersioncolumns,lettingyouseewhatversionofeachpackageisinstalled:>installed.packages()[,c("Package","Version")]PackageVersionacepack"acepack""1.3-2.2"alr3"alr3""1.0.9"base"base""2.4.1"boot"boot""1.2-27"bootstrap"bootstrap""1.0-20"calibrate"calibrate""0.0"car"car""1.2-1"chron"chron""2.3-12"class"class""7.2-30"cluster"cluster""1.11.4"..(etc.).SeeAlsoSeeRecipe3.6forloadingapackageintomemory.3.9InstallingPackagesfromCRANProblemYoufoundapackageonCRAN,andnowyouwanttoinstallitonyourcomputer.SolutionCommandlinewnloadfromWow!eBookoUsetheDinstall.packagesfunction,puttingthenameofthepackageinquotes:>install.packages("packagename")WindowsYoucanalsodownloadandinstallviaPackages→Installpackage(s)...fromthemainmenu.OSXYoucanalsodownloadandinstallviaPackages&Data→PackageInstallerfromthemainmenu.Onallplatforms,youwillbeaskedtoselectaCRANmirror.OnWindowsandOSX,youwillalsobeaskedtoselectthepackagesfordownload.3.9InstallingPackagesfromCRAN|59 System-wideInstallationonLinuxorUnixOnLinuxorUnixsystems,rootprivilegesarerequiredtoinstallpackagesintothesystem-widelibrariesbecausethosedirectoriesarenotusuallywritablebymeremor-tals.Forthatreason,installationsareusuallyperformedbyasystemadministrator.Iftheadministratorisunwillingorunabletodoasystem-wideinstallation,youcanstillinstallpackagesinyourpersonallibrary.Ifyouhaverootprivileges:1.Runsuorsudotostartarootshell.2.StartanRsessionintherootshell.3.Fromthere,executetheinstall.packagesfunction.Ifyoudon’thaverootprivileges,you’llknowveryquickly.Theinstall.packagesfunc-tionwillstop,warningyouthatitcannotwriteintothenecessarydirectories.Thenitwillaskifyouwanttocreateapersonallibraryinstead.Ifyoudo,itwillcreatethenecessarydirectoriesinyourhomedirectoryandinstallthepackagethere.DiscussionInstallingapackagelocallyisthefirststeptowardusingit.Theinstallerwillpromptyouforamirrorsitefromwhichitcandownloadthepackagefiles:---PleaseselectaCRANmirrorforuseinthissession---ItwillthendisplayalistofCRANmirrorsites.Selectoneclosetoyou.TheofficialCRANserverisarelativelymodestmachinegenerouslyhostedbytheDepartmentofStatisticsandMathematicsatWUWien,Vienna,Austria.IfeveryRuserdownloadedfromtheofficialserver,itwouldbuckleundertheload,sotherearenumerousmirrorsitesaroundtheglobe.Youarestronglyencouragedtofindanduseanearbymirror.Ifthenewpackagedependsuponotherpackagesthatarenotalreadyinstalledlocally,thentheRinstallerwillautomaticallydownloadandinstallthoserequiredpackages.Thisisahugebenefitthatfreesyoufromthetedioustaskofidentifyingandresolvingthosedependencies.ThereisaspecialconsiderationwheninstallingonLinuxorUnix.Youcaninstallthepackageeitherinthesystem-widelibraryorinyourpersonallibrary.Packagesinthesystem-widelibraryareavailabletoeveryone;packagesinyourpersonallibraryare(normally)usedonlybyyou.Soapopular,well-testedpackagewouldlikelygointhesystem-widelibrarywhereasanobscureoruntestedpackagewouldgointoyourper-sonallibrary.Bydefault,install.packagesassumesyouareperformingasystem-wideinstall.Toinstallintoyourpersonallibrary,firstcreateadirectoryforthelibrary—forexample,~/lib/R:60|Chapter3:NavigatingtheSoftware $mkdir~/lib$mkdir~/lib/RSettheR_LIBSenvironmentvariablebeforestartingR.Otherwise,itwillnotknowyourlibrary’slocation:$exportR_LIBS=~/lib/R#bashsyntax$setenvR_LIBS~/lib/R#cshsyntaxThen,callinstall.packageswiththelibargumentsettothatdirectory:>install.packages("packagename",lib="~/lib/R")SeeAlsoSeeRecipe1.11forwaystofindrelevantpackagesandRecipe3.6forusingapackageafterinstallingit.3.10SettingaDefaultCRANMirrorProblemYouaredownloadingpackages.YouwanttosetadefaultCRANmirrorsoRdoesnotpromptforoneeachtime.SolutionThissolutionassumesyouhavean.Rprofile,asdescribedinRecipe3.16:1.CallthechooseCRANmirrorfunction:>chooseCRANmirror()RwillpresentalistofCRANmirrors.2.SelectaCRANmirrorfromthelistandpressOK.3.TogettheURLofthemirror,lookatthefirstelementofthereposoption:>options("repos")[[1]][1]4.Addthislinetoyour.Rprofilefile:options(repos="URL")whereURListheURLofthemirror.DiscussionWhenyouinstallpackages,youprobablyusethesameCRANmirroreachtime(namely,themirrorclosesttoyou).YouprobablygettiredofRrepeatedlyaskingyoutoselectamirror.IfyoufollowtheSolution,Rwillstoppromptingforamirrorbecauseitwillhaveadefaultmirror.3.10SettingaDefaultCRANMirror|61 Thereposoptionisthenameofyourdefaultmirror.ThechooseCRANmirrorfunctionhastheimportantsideeffectofsettingthereposoptionaccordingtoyourselection.TheproblemisthatRforgetsthesettingwhenitexits,leavingnopermanentdefault.Bysettingreposinyour.Rprofile,yourestorethesettingeverytimeRstarts.SeeAlsoSeeRecipe3.16formoreaboutthe.Rprofilefileandtheoptionsfunction.3.11SuppressingtheStartupMessageProblemYouaretiredofseeingR’sverbosestartupmessage.SolutionUsethe--quietcommand-lineoptionwhenyoustartR.DiscussionThestartupmessagefromRishandyforbeginnersbecauseitcontainsusefulinfor-mationabouttheRprojectandgettinghelp.Butthenoveltywearsoffprettyquickly.IfyoustartRfromtheshellprompt,usethe--quietoptiontohidethestartupmessage:$R--quiet>OnmyLinuxbox,IaliasedRlikethissoIneverseethestartupmessage:$aliasR="/usr/bin/R--quiet"IfyouarestartingRinWindowsusingashortcut,youcanembedthe--quietoptioninsidetheshortcut.Right-clickontheshortcuticon;selectProperties;selecttheShort-cuttab;and,attheendoftheTargetstring,addthe--quietoption.Becarefultoleaveaspacebetweentheendoftheprogrampathand--quiet.SeeAlsoSeeRecipe1.2.3.12RunningaScriptProblemYoucapturedaseriesofRcommandsinatextfile.Nowyouwanttoexecutethem.62|Chapter3:NavigatingtheSoftware SolutionThesourcefunctioninstructsRtoreadthetextfileandexecuteitscontents:>source("myScript.R")DiscussionWhenyouhavealongorfrequentlyusedpieceofRcode,captureitinsideatextfile.Thatletsyoueasilyrerunthecodewithouthavingtoretypeit.Usethesourcefunctiontoreadandexecutethecode,justasifyouhadtypeditintotheRconsole.Supposethefilehello.Rcontainsthisone,familiargreeting:print("Hello,World!")Thensourcingthefilewillexecutethefilecontents:>source("hello.R")[1]"Hello,World!"Settingecho=TRUEwillechothescriptlinesbeforetheyareexecuted,withtheRpromptshownbeforeeachline:>source("hello.R",echo=TRUE)>print("Hello,World!")[1]"Hello,World!"SeeAlsoSeeRecipe2.13forrunningblocksofRcodeinsidetheGUI.3.13RunningaBatchScriptProblemYouarewritingacommandscript,suchasashellscriptinUnixorOSXoraBATscriptinWindows.Insideyourscript,youwanttoexecuteanRscript.SolutionRuntheRprogramwiththeCMDBATCHsubcommand,givingthescriptnameandtheoutputfilename:$RCMDBATCHscriptfileoutputfileIfyouwanttheoutputsenttostdoutorifyouneedtopasscommand-lineargumentstothescript,considertheRscriptcommandinstead:$Rscriptscriptfilearg1arg2arg33.13RunningaBatchScript|63 DiscussionRisnormallyaninteractiveprogram,onethatpromptstheuserforinputandthendisplaystheresults.SometimesyouwanttorunRinbatchmode,readingcommandsfromascript.Thisisespeciallyusefulinsideshellscripts,suchasscriptsthatincludeastatisticalanalysis.TheCMDBATCHsubcommandputsRintobatchmode,readingfromscriptfileandwritingtooutputfile.Itdoesnotinteractwithauser.Youwilllikelyusecommand-lineoptionstoadjustR’sbatchbehaviortoyourcircum-stances.Forexample,using--quietsilencesthestartupmessagesthatwouldotherwisecluttertheoutput:$RCMDBATCH--quietmyScript.Rresults.outOtherusefuloptionsinbatchmodeincludethefollowing:--slaveLike--quiet,butitmakesRevenmoresilentbyinhibitingechooftheinput.--no-restoreAtstartup,donotrestoretheRworkspace.ThisisimportantifyourscriptexpectsRtobeginwithanemptyworkspace.--no-saveAtexit,donotsavetheRworkspace.Otherwise,Rwillsaveitsworkspaceandoverwritethe.RDatafileintheworkingdirectory.--no-init-fileDonotreadeitherthe.Rprofileor~/.Rprofilefiles.TheCMDBATCHsubcommandnormallycallsproc.timewhenyourscriptcompletes,showingtheexecutiontime.IfthisannoysyouthenendyourscriptbycallingtheqfunctionwithrunLast=FALSE,whichwillpreventthecalltoproc.time.TheCMDBATCHsubcommandhastwolimitations:theoutputalwaysgoestoafile,andyoucannoteasilypasscommand-lineargumentstoyourscript.Ifeitherlimitationisaproblem,considerusingtheRscriptprogramthatcomeswithR.Thefirstcommand-lineargumentisthescriptname,andtheremainingargumentsaregiventothescript:$RscriptmyScript.Rarg1arg2arg3Insidethescript,thecommand-lineargumentscanbeaccessedbycallingcommandArgs,whichreturnstheargumentsasavectorofstrings:argv<-commandArgs(TRUE)TheRscriptprogramtakesthesamecommand-lineoptionsasCMDBATCH,whichwerejustdescribed.64|Chapter3:NavigatingtheSoftware Outputiswrittentostdout,whichRinheritsfromthecallingshellscript,ofcourse.Youcanredirecttheoutputtoafilebyusingthenormalredirection:$Rscript--slavemyScript.Rarg1arg2arg3>results.outHereisasmallRscript,arith.R,thattakestwocommand-lineargumentsandperformsfourarithmeticoperationsonthem:argv<-commandArgs(TRUE)x<-as.numeric(argv[1])y<-as.numeric(argv[2])cat("x=",x," ")cat("y=",y," ")cat("x+y=",x+y," ")cat("x-y=",x-y," ")cat("x*y=",x*y," ")cat("x/y=",x/y," ")Thescriptisinvokedlikethis:$Rscriptarith.R23.1415whichproducesthefollowingoutput:x=2y=3.1415x+y=5.1415x-y=-1.1415x*y=6.283x/y=0.6366385OnLinuxorUnix,youcanmakethescriptfullyself-containedbyplacinga#!lineattheheadwiththepathtotheRscriptprogram.SupposethatRscriptisinstalledin/usr/bin/Rscriptonyoursystem.Thenaddingthislinetoarith.Rmakesitaself-containedscript:#!/usr/bin/Rscript--slaveargv<-commandArgs(TRUE)x<-as.numeric(argv[1])..(etc.).Attheshellprompt,wemarkthescriptasexecutable:$chmod+xarith.RNowwecaninvokethescriptdirectlywithouttheRscriptprefix:$arith.R23.1415SeeAlsoSeeRecipe3.12forrunningascriptfromwithinR.3.13RunningaBatchScript|65 3.14GettingandSettingEnvironmentVariablesProblemYouwanttoseethevalueofanenvironmentvariable,oryouwanttochangeitsvalue.SolutionUsetheSys.getenvfunctiontoseevalues.UseSys.putenvtochangethem:>Sys.getenv("SHELL")SHELL"/bin/bash">Sys.setenv(SHELL="/bin/ksh")DiscussionEnvironmentvariablesareoftenusedonLinuxandUnixtoconfigureandcontrolthesoftware.Eachprocesshasitsownsetofenvironmentvariables,whichareinheritedfromitsparentprocess.YousometimesneedtoseetheenvironmentvariablesettingsforyourRprocessinordertounderstanditsbehavior.Likewise,yousometimesneedtochangethosesettingstomodifythatbehavior.SometimesIstartRinoneplacebutactuallywantthegraphicstoappearinadifferentplace.Forexample,ImightrunRononeLinuxterminalbutwantthegraphicstoappearonalargerdisplaythatanaudiencecanseemoreeasily.OrImightwanttorunRonmyLinuxworkstationandhavethegraphicsappearonacolleague’sworkstation.OnLinux,RusestheXWindowssystemforitsgraphicsdisplays.XWindowschoosesitsdisplaydeviceaccordingtoanenvironmentvariablecalledDISPLAY.WecanuseSys.getenvtoseeitsvalue:>Sys.getenv("DISPLAY")DISPLAY":0.0"Allenvironmentvariablesarestring-valued,andherethevalueis":0.0"—anobscurewayofsayingthattheRsessionisconnectedtodisplay0,screennumber0onmyworkstation.Toredirectgraphicstothelocaldisplayat10.0,wecanchangeDISPLAYinthisway:>Sys.putenv(DISPLAY="localhost:10.0")Similarly,wecouldredirectgraphicstodisplay0,screen0ontheworkstationcalledzeus:>Sys.putenv(DISPLAY="zeus:0.0")Ineitherevent,youmustchangetheDISPLAYvariablebeforedrawingyourgraphic.66|Chapter3:NavigatingtheSoftware 3.15LocatingtheRHomeDirectoryProblemYouneedtoknowtheRhomedirectory,whichiswheretheconfigurationandinstal-lationfilesarekept.SolutionRcreatesanenvironmentvariablecalledR_HOMEthatyoucanaccessbyusingtheSys.getenvfunction:>Sys.getenv("R_HOME")DiscussionMostuserswillneverneedtoknowtheRhomedirectory.ButsystemadministratorsorsophisticatedusersmustknowinordertocheckorchangetheRinstallationfiles.WhenRstarts,itdefinesanenvironmentvariable(notanRvariable)calledR_HOME,whichisthepathtotheRhomedirectory.TheSys.getenvfunctioncanretrieveitsvalue.Hereareexamplesbyplatform.Theexactvaluereportedwillalmostcertainlybedifferentonyourowncomputer:OnWindows>Sys.getenv("R_HOME")R_HOME"C:\PROGRA~1\R\R-21~1.1"OnOSX>Sys.getenv("R_HOME")"/Library/Frameworks/R.framework/Resources"OnLinuxorUnix>Sys.getenv("R_HOME")R_HOME"/usr/lib/R"TheWindowsresultlooksfunkybecauseRreportstheold,DOS-stylecompressedpathname.Thefull,user-friendlypathwouldbeC:ProgramFilesRR-2.10.1inthiscase.OnUnixandOSX,youcanalsoruntheRprogramfromtheshellandusetheRHOMEsubcommandtodisplaythehomedirectory:$RRHOME/usr/lib/RNotethattheRhomedirectoryonUnixandOSXcontainstheinstallationfilesbutnotnecessarilytheRexecutablefile.Theexecutablecouldbein/usr/binwhiletheRhomedirectoryis,forexample,/usr/lib/R.3.15LocatingtheRHomeDirectory|67 3.16CustomizingRProblemYouwanttocustomizeyourRsessionsby,forinstance,changingconfigurationoptionsorpreloadingpackages.SolutionCreateascriptcalled.RprofilethatcustomizesyourRsession.Rwillexecutethe.Rprofilescriptwhenitstarts.Theplacementof.Rprofiledependsuponyourplatform:OSX,Linux,orUnixSavethefileinyourhomedirectory(~/.Rprofile).WindowsSavethefileinyourMyDocumentsdirectory.DiscussionRexecutesprofilescriptswhenitstarts,freeingyoufromrepeatedlyloadingoften-usedpackagesortweakingtheRconfigurationoptions.Youcancreateaprofilescriptcalled.Rprofileandplaceitinyourhomedirectory(OSX,Linux,Unix)oryourMyDocumentsdirectory(WindowsXP)orDocumentsdirec-tory(WindowsVista,Windows7).Thescriptcancallfunctionstocustomizeyoursessions,suchasthissimplescriptthatloadstheMASSpackageandsetstheprompttoR>:require(MASS)options(prompt="R>")Theprofilescriptexecutesinabare-bonesenvironment,sotherearelimitsonwhatitcando.Tryingtoopenagraphicswindowwillfail,forexample,becausethegraphicspackageisnotyetloaded.Also,youshouldnotattemptlong-runningcomputations.Youcancustomizeaparticularprojectbyputtingan.Rprofilefileinthedirectorythatcontainstheprojectfiles.WhenRstartsinthatdirectory,itreadsthelocal.Rprofilefile;thisallowsyoutodoproject-specificcustomizations(e.g.,loadingpackagesneededonlybytheproject).However,ifRfindsalocalprofilethenitdoesnotreadtheglobalprofile.Thatcanbeannoying,butit’seasilyfixed:simplysourcetheglobalprofilefromthelocalprofile.OnUnix,forinstance,thislocalprofilewouldexecutetheglobalprofilefirstandthenexecuteitslocalmaterial:source("~/.Rprofile")##...remainderoflocal.Rprofile...#68|Chapter3:NavigatingtheSoftware SettingOptionsSomecustomizationsarehandledviacallstotheoptionsfunction,whichsetstheRconfigurationoptions.Therearemanysuchoptions,andtheRhelppageforoptionsliststhemall:>help(options)Herearesomeexamples:browser="path"PathofdefaultHTMLbrowserdigits=nSuggestednumberofdigitstoprintwhenprintingnumericvalueseditor="path"Defaulttexteditorprompt="string"Inputpromptrepos="url"URLfordefaultrepositoryforpackageswarn=nControlsdisplayofwarningmessagesLoadingPackagesAnothercommoncustomizationisthepreloadingofpackages.YoumaywantcertainpackagesloadedeverytimeyourunRbecauseyouusethemsooften.Asimplewaytoaccomplishthisisbycallingtherequirefunctioninsideyour.Rprofilescript,likethiscall(whichloadsthetseriespackage):require(tseries)IfrequiregenerateswarningmessagesthatarepollutingyouroutputwhenRstarts,surrounditwithasuppressMessagesfunction.That’llmuzzleit:suppressMessages(require(tseries))Insteadofcallingrequireexplicitly,youcansetaconfigurationparametercalleddefaultPackages.ThisisthelistofpackagesloadedbyRatstartup.Itinitiallycontainsasystem-definedlist.IfyouappendpackagenamestothelistthenRwillloadthem,too,savingyoufromhavingtocalllibraryorrequireyourself.HereisaclipfrommyRprofilethatadjuststhelistofloadedpackages.Ialmostalwaysusethezoopackage,soIappendittothedefaultPackageslist:pkgs<-getOption("defaultPackages")#Getsystemlistofpackagestoloadpkgs<-c(pkgs,"zoo")#Append"zoo"tolistoptions(defaultPackages=pkgs)#Updateconfigurationoptionrm(pkgs)#Cleanupourtempvariable3.16CustomizingR|69 OneadvantageofusingdefaultPackagesisthatyoucancontroltheplacementofthepackagesinthesearchlist.Packagesappendedtotheendareloadedlast,sointhisexamplethezoopackagewillappearattheheadofthesearchlist.(Rememberthatpackagesareinsertedattheheadofthesearchlistwhentheyareloaded.)ThepriceforalwaysloadingthezoopackageisthatRstartsalittlemoreslowly,evenwhenIdon’treallyneedzoo.Inmycase,Ijustwasfedupwithtypinglibrary(zoo)nearlyeverytimeIranR,soIdecidedtheslowerstartupwasagoodtrade-offfortheconvenience.StartupSequenceHereisasimplifiedoverviewofwhathappenswhenRstarts(typehelp(Startup)toseethefulldetails):1.RexecutestheRprofile.sitescript.Thisisthesite-levelscriptthatenablessystemadministratorstooverridedefaultoptionswithlocalizations.Thescript’sfullpathisR_HOME/etc/Rprofile.site.(R_HOMEistheRhomedirectory;seeRecipe3.15.)TheRdistributiondoesnotincludeanRprofile.sitefile.Rather,thesystemadministratorcreatesoneifitisneeded.2.Rexecutesthe.Rprofilescriptintheworkingdirectory;or,ifthatfiledoesnotexist,executesthe.Rprofilescriptinyourhomedirectory.Thisistheuser’sopportunitytocustomizeRforhisorherpurposes.The.Rprofilescriptinthehomedirectoryisusedforglobalcustomizations.The.Rprofilescriptinalower-leveldirectorycanperformspecificcustomizationswhenRisstartedthere;forinstance,custom-izingRwhenstartedinaproject-specificdirectory.3.Rloadstheworkspacesavedin.RData,ifthatfileexistsintheworkingdirectory.Rsavesyourworkspaceinthefilecalled.RDatawhenitexits.Itreloadsyourwork-spacefromthatfile,restoringaccesstoyourlocalvariablesandfunctions.4.Rexecutesthe.Firstfunction,ifyoudefinedone.The.Firstfunctionisausefulplaceforusersorprojectstodefinestartupinitializationcode.Youcandefineitinyour.Rprofileorinyourworkspace.5.Rexecutesthe.First.sysfunction.Thissteploadsthedefaultpackages.Thefunc-tionisinternaltoRandnotnormallychangedbyeitherusersoradministrators.ObservethatRdoesnotloadthedefaultpackagesuntilthefinalstep,whenitexecutesthe.First.sysfunction.Beforethat,onlythebasepackagehasbeenloaded.Thisisakeyfactbecauseitmeansthepreviousstepscannotassumethatpackagesotherthanthebaseareavailable.Italsoexplainswhytryingtoopenagraphicalwindowinyour.Rprofilescriptfails:thegraphicspackagesaren’tloadedyet.SeeAlsoSeeRecipe3.6formoreaboutloadingpackages.SeetheRhelppageforStartup(help(Startup))andtheRhelppageforoptions(help(options)).70|Chapter3:NavigatingtheSoftware

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

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

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