资源描述:
《reilly media] r cookbook data structures》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、CHAPTER5DataStructuresIntroductionYoucangetprettyfarinRjustusingvectors.That’swhatChapter2isallabout.Thischaptermovesbeyondvectorstorecipesformatrices,lists,factors,anddataframes.Ifyouhavepreconceptionsaboutdatastructures,Isuggestyouputthemaside.Rdoesdatastructuresdifferently.Ifyouwanttostud
2、ythetechnicalaspectsofR’sdatastructures,IsuggestreadingRinaNutshell(O’Reilly)andtheRLanguageDefinition.Mynotesherearemoreinformal.ThesearethingsIwishI’dknownwhenIstartedusingR.VectorsHerearesomekeypropertiesofvectors:VectorsarehomogeneousAllelementsofavectormusthavethesametypeor,inRterminolo
3、gy,thesamemode.VectorscanbeindexedbypositionSov[2]referstothesecondelementofv.Vectorscanbeindexedbymultiplepositions,returningasubvectorSov[c(2,3)]isasubvectorofvthatconsistsofthesecondandthirdelements.VectorelementscanhavenamesVectorshaveanamesproperty,thesamelengthasthevectoritself,thatgiv
4、esnamestotheelements:>v<-c(10,20,30)>names(v)<-c("Moe","Larry","Curly")>print(v)MoeLarryCurly10203095IfvectorelementshavenamesthenyoucanselectthembynameContinuingthepreviousexample:>v["Larry"]Larry20ListsListsareheterogeneousListscancontainelementsofdifferenttypes;inRterminology,listelements
5、mayhavedifferentmodes.Listscanevencontainotherstructuredobjects,suchaslistsanddataframes;thisallowsyoutocreaterecursivedatastructures.ListscanbeindexedbypositionSolst[[2]]referstothesecondelementoflst.Notethedoublesquarebrackets.ListsletyouextractsublistsSolst[c(2,3)]isasublistoflstthatconsi
6、stsofthesecondandthirdelements.Notethesinglesquarebrackets.ListelementscanhavenamesBothlst[["Moe"]]andlst$Moerefertotheelementnamed“Moe”.Sincelistsareheterogeneousandsincetheirelementscanberetrievedbyname,alistislikeadictionaryorhashorlookuptableinotherprogramminglanguages(Recipe5.9).What’ss
7、urprising(andcool)isthatinR,unlikemostofthoseotherprogramminglanguages,listscanalsobeindexedbyposition.Mode:PhysicalTypeInR,everyobjecthasamode,whichindicateshowitisstoredinmemory:asanumber,asacharacterstring,asalistofpointerstootherobjects,asafunc