reilly media] r cookbook strings and dates

reilly media] r cookbook strings and dates

ID:7290941

大小:358.68 KB

页数:16页

时间:2018-02-10

上传者:U-5649
reilly media] r cookbook strings and dates_第1页
reilly media] r cookbook strings and dates_第2页
reilly media] r cookbook strings and dates_第3页
reilly media] r cookbook strings and dates_第4页
reilly media] r cookbook strings and dates_第5页
资源描述:

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

CHAPTER7StringsandDatesIntroductionStrings?Dates?Inastatisticalprogrammingpackage?Assoonasyoureadfilesorprintreports,youneedstrings.Whenyouworkwithreal-worldproblems,youneeddates.Rhasfacilitiesforbothstringsanddates.Theyareclumsycomparedtostring-orientedlanguagessuchasPerl,butthenit’samatteroftherighttoolforthejob.Iwouldn’twanttoperformlogisticregressioninPerl.ClassesforDatesandTimesRhasavarietyofclassesforworkingwithdatesandtimes;whichisniceifyoupreferhavingachoicebutannoyingifyoupreferlivingsimply.Thereisacriticaldistinctionamongtheclasses:somearedate-onlyclasses,somearedatetimeclasses.Allclassescanhandlecalendardates(e.g.,March15,2010),butnotallcanrepresentadatetime(11:45AMonMarch1,2010).ThefollowingclassesareincludedinthebasedistributionofR:DateTheDateclasscanrepresentacalendardatebutnotaclocktime.Itisasolid,general-purposeclassforworkingwithdates,includingconversions,formatting,basicdatearithmetic,andtime-zonehandling.Mostofthedate-relatedrecipesinthisbookarebuiltontheDateclass.POSIXctThisisadatetimeclass,anditcanrepresentamomentintimewithanaccuracyofonesecond.Internally,thedatetimeisstoredasthenumberofsecondssinceJanuary1,1970,andsoisaverycompactrepresentation.Thisclassisrecommen-dedforstoringdatetimeinformation(e.g.,indataframes).161 POSIXltThisisalsoadatetimeclass,buttherepresentationisstoredinanine-elementlistthatincludestheyear,month,day,hour,minute,andsecond.Thatrepresentationmakesiteasytoextractdateparts,suchasthemonthorhour.Obviously,thisrepresentationismuchlesscompactthanthePOSIXctclass;henceitisnormallyusedforintermediateprocessingandnotforstoringdata.Thebasedistributionalsoprovidesfunctionsforeasilyconvertingbetweenrepresen-tations:as.Date,as.POSIXct,andas.POSIXlt.ThefollowingpackagesareavailablefordownloadingfromCRAN:chronThechronpackagecanrepresentbothdatesandtimesbutwithouttheaddedcomplexitiesofhandlingtimezonesanddaylightsavingstime.It’sthereforeeasiertousethanDatebutlesspowerfulthanPOSIXctandPOSIXlt.Itwouldbeusefulforworkineconometricsortimeseriesanalysis.lubridateThisisarelativelynew,general-purposepackage.It’sdesignedtomakeworkingwithdatesandtimeseasierwhilekeepingtheimportantbellsandwhistlessuchastimezones.It’sespeciallycleverregardingdatetimearithmetic.mondateThisisaspecializedpackageforhandlingdatesinunitsofmonthsinadditiontodaysandyears.Suchneedsariseinaccountingandactuarialwork,forexample,wheremonth-by-monthcalculationsareneeded.timeDateThisisahigh-poweredpackagewithwell-thought-outfacilitiesforhandlingdatesandtimes,includingdatearithmetic,businessdays,holidays,conversions,andgeneralizedhandlingoftimezones.ItwasoriginallypartoftheRmetricssoftwareforfinancialmodeling,whereprecisionindatesandtimesiscritical.Ifyouhaveademandingneedfordatefacilities,considerthispackage.Whichclassshouldyouselect?Thearticle“DateandTimeClassesinR”byGrothen-dieckandPetzoldtoffersthisgeneraladvice:Whenconsideringwhichclasstouse,alwayschoosetheleastcomplexclassthatwillsupporttheapplication.Thatis,useDateifpossible,otherwiseusechronandotherwiseusethePOSIXclasses.Suchastrategywillgreatlyreducethepotentialforerrorandincreasethereliabilityofyourapplication.SeeAlsoSeehelp(DateTimeClasses)formoredetailsregardingthebuilt-infacilities.SeetheJune2004article“DateandTimeClassesinR”byGaborGrothendieckandThomasPet-zoldtforagreatintroductiontothedateandtimefacilities.TheJune2001article162|Chapter7:StringsandDates “Date-TimeClasses”byBrianRipleyandKurtHornikdiscussesthetwoPOSIXclassesinparticular.7.1GettingtheLengthofaStringProblemYouwanttoknowthelengthofastring.SolutionUsethencharfunction,notthelengthfunction.DiscussionThencharfunctiontakesastringandreturnsthenumberofcharactersinthestring:>nchar("Moe")[1]3>nchar("Curly")[1]5Ifyouapplynchartoavectorofstrings,itreturnsthelengthofeachstring:>s<-c("Moe","Larry","Curly")>nchar(s)[1]355Youmightthinkthelengthfunctionreturnsthelengthofastring.Nope—itreturnsthelengthofavector.Whenyouapplythelengthfunctiontoasinglestring,Rreturnsthevalue1becauseitviewsthatstringasasingletonvector—avectorwithoneelement:>length("Moe")[1]1>length(c("Moe","Larry","Curly"))[1]37.2ConcatenatingStringsProblemYouwanttojointogethertwoormorestringsintoonestring.SolutionUsethepastefunction.7.2ConcatenatingStrings|163 DiscussionThepastefunctionconcatenatesseveralstringstogether.Inotherwords,itcreatesanewstringbyjoiningthegivenstringsendtoend:>paste("Everybody","loves","stats.")[1]"Everybodylovesstats."Bydefault,pasteinsertsasinglespacebetweenpairsofstrings,whichishandyifthat’swhatyouwantandannoyingotherwise.Thesepargumentletsyouspecifyadifferentseparator.Useanemptystring("")torunthestringstogetherwithoutseparation:>paste("Everybody","loves","stats.",sep="-")[1]"Everybody-loves-stats.">paste("Everybody","loves","stats.",sep="")[1]"Everybodylovesstats."Thefunctionisveryforgivingaboutnonstringarguments.Ittriestoconvertthemtostringsusingtheas.characterfunction:>paste("Thesquarerootoftwicepiisapproximately",sqrt(2*pi))[1]"Thesquarerootoftwicepiisapproximately2.506628274631"Ifoneormoreargumentsarevectorsofstrings,pastewillgenerateallcombinationsofthearguments:>stooges<-c("Moe","Larry","Curly")>paste(stooges,"loves","stats.")[1]"Moelovesstats.""Larrylovesstats.""Curlylovesstats."Sometimesyouwanttojoineventhosecombinationsintoone,bigstring.Thecollapseparameterletsyoudefineatop-levelseparatorandinstructspastetoconcat-enatethegeneratedstringsusingthatseparator:>paste(stooges,"loves","stats",collapse=",and")[1]"Moelovesstats,andLarrylovesstats,andCurlylovesstats"7.3ExtractingSubstringsProblemYouwanttoextractaportionofastringaccordingtoposition.SolutionUsesubstr(string,start,end)toextractthesubstringthatbeginsatstartandendsatend.DiscussionThesubstrfunctiontakesastring,astartingpoint,andanendingpoint.Itreturnsthesubstringbetweenthestartingtoendingpoints:164|Chapter7:StringsandDates >substr("Statistics",1,4)#Extractfirst4characters[1]"Stat">substr("Statistics",7,10)#Extractlast4characters[1]"tics"JustlikemanyRfunctions,substrletsthefirstargumentbeavectorofstrings.Inthatcase,itappliesitselftoeverystringandreturnsavectorofsubstrings:>ss<-c("Moe","Larry","Curly")>substr(ss,1,3)#Extractfirst3charactersofeachstring[1]"Moe""Lar""Cur"Infact,alltheargumentscanbevectors,inwhichcasesubstrwilltreatthemasparallelvectors.Fromeachstring,itextractsthesubstringdelimitedbythecorrespondingen-triesinthestartingandendingpoints.Thiscanfacilitatesomeusefultricks.Forex-ample,thefollowingcodesnippetextractsthelasttwocharactersfromeachstring;eachsubstringstartsonthepenultimatecharacteroftheoriginalstringandendsonthefinalcharacter:>cities<-c("NewYork,NY","LosAngeles,CA","Peoria,IL")>substr(cities,nchar(cities)-1,nchar(cities))[1]"NY""CA""IL"Youcanextendthistrickintomind-numbingterritorybyexploitingtheRecyclingRule,butIsuggestyouavoidthetemptation.7.4SplittingaStringAccordingtoaDelimiterProblemYouwanttosplitastringintosubstrings.Thesubstringsareseparatedbyadelimiter.SolutionUsestrsplit,whichtakestwoarguments—thestringandthedelimiterofthesub-strings:>strsplit(string,delimiter)Thedelimitercanbeeitherasimplestringoraregularexpression.DiscussionItiscommonforastringtocontainmultiplesubstringsseparatedbythesamedelimiter.Oneexampleisafilepath,whosecomponentsareseparatedbyslashes(/):>path<-"/home/mike/data/trials.csv"Wecansplitthatpathintoitscomponentsbyusingstrsplitwithadelimiterof/:>strsplit(path,"/")[[1]][1]"""home""mike""data""trials.csv"7.4SplittingaStringAccordingtoaDelimiter|165 Noticethatthefirst“component”isactuallyanemptystringbecausenothingprecededthefirstslash.Alsonoticethatstrsplitreturnsalistandthateachelementofthelistisavectorofsubstrings.Thistwo-levelstructureisnecessarybecausethefirstargumentcanbeavectorofstrings.Eachstringissplitintoitssubstrings(avector);thenthosevectorsarereturnedinalist.Thisexamplesplitsthreefilepathsandreturnsathree-elementlist:>paths<-c("/home/mike/data/trials.csv",+"/home/mike/data/errors.csv",+"/home/mike/corr/reject.doc")>strsplit(paths,"/")[[1]][1]"""home""mike""data""trials.csv"[[2]][1]"""home""mike""data""errors.csv"[[3]][1]"""home""mike""corr""reject.doc"Thesecondargumentofstrsplit(thedelimiterargument)isactuallymuchmorepowerfulthantheseexamplesindicate.Itcanbearegularexpression,lettingyoumatchpatternsfarmorecomplicatedthanasimplestring.Infact,todefeattheregularex-pressionfeature(anditsinterpretationofspecialcharacters)youmustincludethefixed=TRUEargument.SeeAlsoTolearnmoreaboutregularexpressionsinR,seethehelppageforregexp.SeeO’Reilly’sMasteringRegularExpressions,byJeffreyE.F.Friedltolearnmoreaboutregularexpressionsingeneral.7.5ReplacingSubstringsProblemWithinastring,youwanttoreplaceonesubstringwithanother.SolutionUsesubtoreplacethefirstinstanceofasubstring:>sub(old,new,string)Usegsubtoreplaceallinstancesofasubstring:>gsub(old,new,string)166|Chapter7:StringsandDates DiscussionThesubfunctionfindsthefirstinstanceoftheoldsubstringwithinstringandreplacesitwiththenewsubstring:>s<-"Curlyisthesmartone.Curlyisfunny,too.">sub("Curly","Moe",s)[1]"Moeisthesmartone.Curlyisfunny,too."gsubdoesthesamething,butitreplacesallinstancesofthesubstring(aglobalreplace),notjustthefirst:>gsub("Curly","Moe",s)[1]"Moeisthesmartone.Moeisfunny,too."Toremoveasubstringaltogether,simplysetthenewsubstringtobeempty:>sub("andSAS","","Forreallytoughproblems,youneedRandSAS.")[1]"Forreallytoughproblems,youneedR."Theoldargumentcanberegularexpression,whichallowsyoutomatchpatternsmuchmorecomplicatedthanasimplestring.Thisisactuallyassumedbydefault,soyoumustsetthefixed=TRUEargumentifyoudon’twantsubandgsubtointerpretoldasaregularexpression.SeeAlsoTolearnmoreaboutregularexpressionsinR,seethehelppageforregexp.SeeMas-teringRegularExpressionstolearnmoreaboutregularexpressionsingeneral.7.6SeeingtheSpecialCharactersinaStringProblemYourstringcontainsspecialcharactersthatareunprintable.Youwanttoknowwhattheyare.SolutionUseprinttoseethespecialcharactersinastring.Thecatfunctionwillnotrevealthem.DiscussionIonceencounteredabizarresituationinwhichastringcontained,unbeknownsttome,unprintablecharacters.MyRscriptusedcattodisplaythestring,andthescriptoutputwasgarbleduntilIrealizedtherewereunprintablecharactersinthestring.7.6SeeingtheSpecialCharactersinaString|167 Inthisexample,thestringseemstocontain13charactersbutcatshowsonlya6-characteroutput:>nchar(s)[1]13>cat(s)secondThereasonisthatthestringcontainsspecialcharacters,whicharecharactersthatdonotdisplaywhenprinted.Whenweuseprint,itusesescapes(backslashes)toshowthespecialcharacters:>print(s)[1]"firstrsecond "Noticethatthestringcontainsareturncharacter(r)inthemiddle,so“first”isover-writtenby“second”whencatdisplaysthestring.7.7GeneratingAllPairwiseCombinationsofStringsProblemYouhavetwosetsofstrings,andyouwanttogenerateallcombinationsfromthosetwosets(theirCartesianproduct).SolutionUsetheouterandpastefunctionstogethertogeneratethematrixofallpossiblecombinations:>m<-outer(strings1,strings2,paste,sep="")DiscussionTheouterfunctionisintendedtoformtheouterproduct.However,itallowsathirdargumenttoreplacesimplemultiplicationwithanyfunction.Inthisrecipewereplacemultiplicationwithstringconcatenation(paste),andtheresultisallcombinationsofstrings.Supposeyouhavefourtestsitesandthreetreatments:>locations<-c("NY","LA","CHI","HOU")>treatments<-c("T1","T2","T3")Wecanapplyouterandpastetogenerateallcombinationsoftestsitesandtreatments:>outer(locations,treatments,paste,sep="-")[,1][,2][,3][1,]"NY-T1""NY-T2""NY-T3"[2,]"LA-T1""LA-T2""LA-T3"[3,]"CHI-T1""CHI-T2""CHI-T3"[4,]"HOU-T1""HOU-T2""HOU-T3"168|Chapter7:StringsandDates Thefourthargumentofouterispassedtopaste.Inthiscase,wepassedsep="-"inordertodefineahyphenastheseparatorbetweenthestrings.Theresultofouterisamatrix.Ifyouwantthecombinationsinavectorinstead,flattenthematrixusingtheas.vectorfunction.Inthespecialcasewhenyouarecombiningasetwithitselfandorderdoesnotmatter,theresultwillbeduplicatecombinations:>outer(treatments,treatments,paste,sep="-")[,1][,2][,3][1,]"T1-T1""T1-T2""T1-T3"[2,]"T2-T1""T2-T2""T2-T3"[3,]"T3-T1""T3-T2""T3-T3"Butsupposewewantalluniquepairwisecombinationsoftreatments.Wecaneliminatetheduplicatesbyremovingthelowertriangle(oruppertriangle).Thelower.trifunc-tionidentifiesthattriangle,soinvertingitidentifiesallelementsoutsidethelowertriangle:>m<-outer(treatments,treatments,paste,sep="-")>m[!lower.tri(m)][1]"T1-T1""T1-T2""T2-T2""T1-T3""T2-T3""T3-T3"SeeAlsoSeeRecipe7.2forusingpastetogeneratecombinationsofstrings.7.8GettingtheCurrentDateProblemYouneedtoknowtoday’sdate.SolutionTheSys.Datefunctionreturnsthecurrentdate:>Sys.Date()[1]"2010-02-11"DiscussionTheSys.DatefunctionreturnsaDateobject.Intheprecedingexampleitseemstoreturnastringbecausetheresultisprintedinsidedoublequotes.Whatreallyhappened,however,isthatSys.DatereturnedaDateobjectandthenRconvertedthatobjectintoastringforprintingpurposes.YoucanseethisbycheckingtheclassoftheresultfromSys.Date:>class(Sys.Date())[1]"Date"7.8GettingtheCurrentDate|169 SeeAlsoSeeRecipe7.10.7.9ConvertingaStringintoaDateProblemYouhavethestringrepresentationofadate,suchas“2010-12-31”,andyouwanttoconvertthatintoaDateobject.SolutionYoucanuseas.Date,butyoumustknowtheformatofthestring.Bydefault,as.Dateassumesthestringlookslikeyyyy-mm-dd.Tohandleotherformats,youmustspecifytheformatparameterofas.Date.Useformat="%m/%d/%Y"ifthedateisinAmericanstyle,forinstance.DiscussionThisexampleshowsthedefaultformatassumedbyas.Date,whichistheISO8601standardformatofyyyy-mm-dd:>as.Date("2010-12-31")[1]"2010-12-31"Theas.DatefunctionreturnsaDateobjectthatisherebeingconvertedbacktoastringforprinting;thisexplainsthedoublequotesaroundtheoutput.Thestringcanbeinotherformats,butyoumustprovideaformatargumentsothatas.Datecaninterpretyourstring.Seethehelppageforthestftimefunctionfordetailsaboutallowedformats.BeingasimpleAmerican,IoftenmistakenlytrytoconverttheusualAmericandateformat(mm/dd/yyyy)intoaDateobject,withtheseunhappyresults:>as.Date("12/31/2010")ErrorincharToDate(x):characterstringisnotinastandardunambiguousformatHereisthecorrectwaytoconvertanAmerican-styledate:>as.Date("12/31/2010",format="%m/%d/%Y")[1]"2010-12-31"ObservethattheYintheformatstringiscapitalizedtoindicatea4-digityear.Ifyou’reusing2-digityears,specifyalowercasey.170|Chapter7:StringsandDates 7.10ConvertingaDateintoaStringProblemYouwanttoconvertaDateobjectintoacharacterstring,usuallybecauseyouwanttoprintthedate.SolutionUseeitherformatoras.character:>format(Sys.Date())[1]"2010-04-01">as.character(Sys.Date())[1]"2010-04-01"Bothfunctionsallowaformatargumentthatcontrolstheformatting.Useformat="%m/%d/%Y"togetAmerican-styledates,forexample:>format(Sys.Date(),format="%m/%d/%Y")[1]"04/01/2010"DiscussionTheformatargumentdefinestheappearanceoftheresultingstring.Normalcharacters,suchasslash(/)orhyphen(-)aresimplycopiedtotheoutputstring.Eachtwo-lettercombinationofapercentsign(%)followedbyanothercharacterhasspecialmeaning.Somecommononesare:%bAbbreviatedmonthname(“Jan”)%BFullmonthname(“January”)%dDayasatwo-digitnumber%mMonthasatwo-digitnumber%yYearwithoutcentury(00–99)%YYearwithcenturySeethehelppageforthestrftimefunctionforacompletelistofformattingcodes.7.10ConvertingaDateintoaString|171 7.11ConvertingYear,Month,andDayintoaDateProblemYouhaveadaterepresentedbyitsyear,month,andday.YouwanttomergetheseelementsintoasingleDateobjectrepresentation.SolutionUsetheISOdatefunction:>ISOdate(year,month,day)TheresultisaPOSIXctobjectthatyoucanconvertintoaDateobject:>as.Date(ISOdate(year,month,day))DiscussionItiscommonforinputdatatocontaindatesencodedasthreenumbers:year,month,andday.TheISOdatefunctioncancombinethemintoaPOSIXctobject:>ISOdate(2012,2,29)[1]"2012-02-2912:00:00GMT"YoucankeepyourdateinthePOSIXctformat.However,whenworkingwithpuredates(notdatesandtimes),IoftenconverttoaDateobjectandtruncatetheunusedtimeinformation:>as.Date(ISOdate(2012,2,29))[1]"2012-02-29"TryingtoconvertaninvaliddateresultsinNA:>ISOdate(2013,2,29)#Oops!2013isnotaleapyear[1]NAISOdatecanprocessentirevectorsofyears,months,anddays,whichisquitehandyformassconversionofinputdata.Thefollowingexamplestartswiththeyear/month/daynumbersforthethirdWednesdayinJanuaryofseveralyearsandthencombinesthemallintoDateobjects:>years[1]20102011201220132014>months[1]11111>days[1]1521201817>ISOdate(years,months,days)[1]"2010-01-1512:00:00GMT""2011-01-2112:00:00GMT"[3]"2012-01-2012:00:00GMT""2013-01-1812:00:00GMT"[5]"2014-01-1712:00:00GMT">as.Date(ISOdate(years,months,days))[1]"2010-01-15""2011-01-21""2012-01-20""2013-01-18""2014-01-17"172|Chapter7:StringsandDates PuristswillnotethatthevectorofmonthsisredundantandthatthelastexpressioncanthereforebefurthersimplifiedbyinvokingtheRecyclingRule:>as.Date(ISOdate(years,1,days))[1]"2010-01-15""2011-01-21""2012-01-20""2013-01-18""2014-01-17"Thisrecipecanalsobeextendedtohandleyear,month,day,hour,minute,andseconddatabyusingtheISOdatetimefunction(seethehelppagefordetails):>ISOdatetime(year,month,day,hour,minute,second)7.12GettingtheJulianDateProblemGivenaDateobject,youwanttoextracttheJuliandate—whichis,inR,thenumberofdayssinceJanuary1,1970.SolutionEitherconverttheDateobjecttoanintegerorusethejulianfunction:>d<-as.Date("2010-03-15")>as.integer(d)[1]14683>julian(d)[1]14683attr(,"origin")[1]"1970-01-01"DiscussionAJulian“date”issimplythenumberofdayssinceamore-or-lessarbitrarystartingpoint.InthecaseofR,thatstartingpointisJanuary1,1970,thesamestartingpointasUnixsystems.SotheJuliandateforJanuary1,1970iszero,asshownhere:>as.integer(as.Date("1970-01-01"))[1]0>as.integer(as.Date("1970-01-02"))[1]1>as.integer(as.Date("1970-01-03"))[1]2..(etc.).7.12GettingtheJulianDate|173 7.13ExtractingthePartsofaDateProblemGivenaDateobject,youwanttoextractadatepartsuchasthedayoftheweek,thedayoftheyear,thecalendarday,thecalendarmonth,orthecalendaryear.SolutionConverttheDateobjecttoaPOSIXltobject,whichisalistofdateparts.Thenextractthedesiredpartfromthatlist:>d<-as.Date("2010-03-15")>p<-as.POSIXlt(d)>p$mday#Dayofthemonth[1]15>p$mon#Month(0=January)[1]2>p$year+1900#Year[1]2010DiscussionThePOSIXltobjectrepresentsadateasalistofdateparts.ConvertyourDateobjecttoPOSIXltbyusingtheas.POSIXltfunction,whichwillgiveyoualistwiththesemembers:secSeconds(0–61)minMinutes(0–59)hourHours(0–23)mdayDayofthemonth(1–31)monMonth(0–11)yearYearssince1900wdayDayoftheweek(0–6,0=Sunday)ydayDayoftheyear(0–365)isdstDaylightsavingstimeflag174|Chapter7:StringsandDates Usingthesedateparts,wecanlearnthatApril1,2010,isaThursday(wday=4)andthe91stdayoftheyear(becauseyday=0onJanuary1):>d<-as.Date("2010-04-01")>as.POSIXlt(d)$wday[1]4>as.POSIXlt(d)$yday[1]90Acommonmistakeisfailingtoadd1900totheyear,givingtheimpressionyouarelivingalong,longtimeago:>as.POSIXlt(d)$year#Oops![1]110>as.POSIXlt(d)$year+1900[1]20107.14CreatingaSequenceofDatesProblemYouwanttocreateasequenceofdates,suchasasequenceofdaily,monthly,orannualdates.SolutionTheseqfunctionisagenericfunctionthathasaversionforDateobjects.ItcancreateaDatesequencesimilarlytothewayitcreatesasequenceofnumbers.DiscussionAtypicaluseofseqspecifiesastartingdate(from),endingdate(to),andincrementwnloadfromWow!eBook(by).Anincrementof1indicatesdailydates:oD>s<-as.Date("2012-01-01")>e<-as.Date("2012-02-01")>seq(from=s,to=e,by=1)#Onemonthofdates[1]"2012-01-01""2012-01-02""2012-01-03""2012-01-04""2012-01-05""2012-01-06"[7]"2012-01-07""2012-01-08""2012-01-09""2012-01-10""2012-01-11""2012-01-12"[13]"2012-01-13""2012-01-14""2012-01-15""2012-01-16""2012-01-17""2012-01-18"[19]"2012-01-19""2012-01-20""2012-01-21""2012-01-22""2012-01-23""2012-01-24"[25]"2012-01-25""2012-01-26""2012-01-27""2012-01-28""2012-01-29""2012-01-30"[31]"2012-01-31""2012-02-01"Anothertypicalusespecifiesastartingdate(from),increment(by),andnumberofdates(length.out):>seq(from=s,by=1,length.out=7)#Dates,oneweekapart[1]"2012-01-01""2012-01-02""2012-01-03""2012-01-04""2012-01-05""2012-01-06"[7]"2012-01-07"7.14CreatingaSequenceofDates|175 Theincrement(by)isflexibleandcanbespecifiedindays,weeks,months,oryears:>seq(from=s,by="month",length.out=12)#Firstofthemonthforoneyear[1]"2012-01-01""2012-02-01""2012-03-01""2012-04-01""2012-05-01""2012-06-01"[7]"2012-07-01""2012-08-01""2012-09-01""2012-10-01""2012-11-01""2012-12-01">seq(from=s,by="3months",length.out=4)#Quarterlydatesforoneyear[1]"2012-01-01""2012-04-01""2012-07-01""2012-10-01">seq(from=s,by="year",length.out=10)#Year-startdatesforonedecade[1]"2012-01-01""2013-01-01""2014-01-01""2015-01-01""2016-01-01""2017-01-01"[7]"2018-01-01""2019-01-01""2020-01-01""2021-01-01"Becarefulwithby="month"nearmonth-end.Inthisexample,theendofFebruaryover-flowsintoMarch,whichisprobablynotwhatyouwanted:>seq(as.Date("2010-01-29"),by="month",len=3)[1]"2010-01-29""2010-03-01""2010-03-29"176|Chapter7:StringsandDates

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

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

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