How to Use rep() Function in R - R-Lang

文章推薦指數: 80 %
投票人數:10人

The rep() is a built-in generic R function that replicates the values in the provided vector. The rep() method takes a vector as an argument and ... Skiptocontent Menu AboutUs ContactUs TermsofService PrivacyPolicy Therep()isaniterationfunctioninR.Thetermiterationmeansrepetition. AniterationisacoreaspectofR.Theregularloopsarelikeforloop,whileloopiscostlyintimeandmemorymanagement. Therep()functionisagoodvectorizedalternativemethodwhosegoalistoachieveiteration.Vectorizedmethodsoperateonallthevectorelementsconcurrently,andvectorizedcomputationsalwaysgetfasterresults. repinR Therep()isabuilt-ingenericRfunctionthatreplicatesthevaluesintheprovidedvector. Therep()methodtakesavectorasanargumentandreturnsthereplicatedvalues.Thus,the rep()isavectorizedloopingfunctionwhoseonlygoalistoachieveiterationwithoutcostingtimeandmemory. Therep()functioninRhastwofaster-simplifiedversions. rep.int() rep_len() Syntax rep(rv,…) Parameters Therep()functiontakesamaximumoftwoarguments. The rv isavector(ofanymode,includingalist)orafactor. The(…) arefurtherargumentstobepassedtoorfromothermethods.Forexample,itcanbeoneofthefollowing. times:Itisaninteger-valuedvectorgivingthe(non-negative)numberoftimestorepeateachitemifoflength.Forexample,length(x),ortorepeatthewholevectorifoflength1.  length.out: Itisanon-negativeinteger—thedesiredlengthoftheoutputvector.  each:Itisanon-negativeinteger.Eachitemofxisrepeatedeachtime. Example rep(11,4) Output [1]11111111 Inthisexample,wearerepeatingvector11fourtimes. TorepeatNAvaluesmorethanonetime,usetherep()function. rep(NA,5) Output [1]NANANANANA RepeatcountingfromnumbertonumberinR Repeatthecountingnumbersfrom1to4threetimes. rep(1:4,3) Output  [1]123412341234 Youcanseethat1through4isrepeatedfourtimes. RepeatvectorwithanincompletecycleinR Torepeatavectorwithanincompletecycle,usethe length.out argumentintherep()function. rep(1:4,3,length.out=9) Output [1]123412341 Byprovidinglength.outargument,youcanrestrictthelengthoftheoutput.So,forexample,youcanseethatthecycleisincompletebecauseoutputshouldconsistof12integers,butinstead,itcontains9integers. Passing each argumenttotherep()function Eachparameterisanon-negativeinteger.Thus,eachelementofxisrepeatedeachtime. rep(1:4,each=2) Output [1]11223344 Youcanseethateachelementfrom1to4isrepeated2times. Automatedlengthrepetition Avectorcanexpandtoabiasedpanelbyreplacingthelengthparameterwithavectorthatdefinesthenumberoftimeseachiteminthevectorwillrepeat. rep(1:4,1:4) Output  [1]1223334444 Here,youcanseethat1appears1time,2twotimes,3threetimes,and4fourtimes. Usingtherep()functiontoreplicatealist Youcanusetherep()functiontoreplicatealistinR. data



請為這篇文章評分?