Table Of ContentUse R!
SeriesEditors:
RobertGentleman KurtHornik GiovanniG.Parmigiani
Forfurthervolumes:
http://www.springer.com/series/6991
Dirk Eddelbuettel
Seamless R and C++
Integration with Rcpp
123
DirkEddelbuettel
RiverForest
Illinois,USA
ISBN978-1-4614-6867-7 ISBN978-1-4614-6868-4 (eBook)
DOI10.1007/978-1-4614-6868-4
SpringerNewYorkHeidelbergDordrechtLondon
LibraryofCongressControlNumber:2013933242
©TheAuthor2013
Thisworkissubjecttocopyright.AllrightsarereservedbythePublisher,whetherthewholeorpartof
thematerialisconcerned,specificallytherightsoftranslation,reprinting,reuseofillustrations,recitation,
broadcasting,reproductiononmicrofilmsorinanyotherphysicalway,andtransmissionorinformation
storageandretrieval,electronicadaptation,computersoftware,orbysimilarordissimilarmethodology
nowknownorhereafterdeveloped.Exemptedfromthislegalreservationarebriefexcerptsinconnection
with reviews or scholarly analysis or material supplied specifically for the purpose of being entered
and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of
this publication or parts thereof is permitted only under the provisions of the Copyright Law of the
Publisher’slocation,initscurrentversion,andpermissionforusemustalwaysbeobtainedfromSpringer.
PermissionsforusemaybeobtainedthroughRightsLinkattheCopyrightClearanceCenter.Violations
areliabletoprosecutionundertherespectiveCopyrightLaw.
Theuseofgeneraldescriptivenames,registerednames,trademarks,servicemarks,etc.inthispublication
doesnotimply,evenintheabsenceofaspecificstatement,thatsuchnamesareexemptfromtherelevant
protectivelawsandregulationsandthereforefreeforgeneraluse.
Whiletheadviceandinformationinthisbookarebelievedtobetrueandaccurateatthedateofpub-
lication,neithertheauthorsnortheeditorsnorthepublishercanacceptanylegalresponsibilityforany
errorsoromissionsthatmaybemade.Thepublishermakesnowarranty,expressorimplied,withrespect
tothematerialcontainedherein.
Printedonacid-freepaper
SpringerispartofSpringerScience+BusinessMedia(www.springer.com)
To Lisa,Annaand Julia
Preface
RcppisanRadd-onpackagewhichfacilitatesextendingRwithC++functions.
Itisbeingusedforanythingfromsmallandquicklyconstructedadd-onfunctions
written either to fluidly experimentwith something new or to accelerate comput-
ing by replacing an R function with its C++ equivalent to large-scale bindings
for existing libraries, or as a building block in entirely new research computing
environments.
Whilestillrelativelynewasaproject,Rcpphasalreadybecomewidelydeployed
among users and developersin the R community. Rcpp is now the most popular
languageextensionfortheRsystemandusedbyover100CRANpackagesaswell
astenBioConductorpackages.
ThisbooksaimstoprovideasolidintroductiontoRcpp.
TargetAudience
ThisbookisforRuserswhowouldliketoextendRwithC++code.Somefamil-
iaritywithRiscertainlyhelpful;anumberofotherbookscanproviderefreshersor
specificintroductions.C++knowledgeisalsohelpful,thoughnotstrictlyrequired.
AnappendixprovidesaverybriefintroductionforC++tothosefamiliaronlywith
theRlanguage.
ThebookshouldalsobehelpfultothosecomingtoRwithmoreofaC++pro-
grammingbackground.However,additionalbackgroundreadingmayberequiredto
obtainafirmergroundinginRitself.Chambers(2008)isagoodintroductiontothe
philosophybehindthe R system anda helpfulsource in orderto acquire a deeper
understanding.
Theremayalso besomereaderswhowouldliketosee howRcppworksinter-
nally.Coveringthataspect,however,requiresafairlysubstantialC++contentand
isnotwhatthisbookistryingtoprovide.Thefocusofthisbookisclearlyonhow
touseRcpp.
vii
viii Preface
HistoricalContext
Rcpp first appeared in 2005 as a (fairly small when comparedto its currentsize)
contribution by Dominick Samperi to the RQuantLib package started by Eddel-
buettel in 2002 (Eddelbuettel and Nguyen 2012). Rcpp became a CRAN pack-
ageinitsownnameinearly2006.Severalreleases(allprovidedbySamperi)fol-
lowedinquicksuccessionunderthenameRcpp.Thepackagewasthenrenamedto
RcppTemplate;severalmorereleasesfollowedduring2006underthe new name.
However,nonewreleasesweremadeduring2007,2008,ormostof2009.Follow-
ingafewupdatesinlate2009,theRcppTemplatepackagehassincebeenarchived
onCRANforlackofactivemaintenance.
Given the continued use of the package, Eddelbuettel decided to revitalize it.
Newreleases,usingtheoriginalnameRcpp,startedinNovember2008.Thesein-
cluded an improvedbuild and distribution process, additionaldocumentation,and
newfunctionality—whileretainingtheexisting“classicRcpp”interface.Whilenot
describedhere,thisAPIwillcontinuetobeprovidedandsupportedviatheRcpp-
Classicpackage(EddelbuettelandFranc¸ois2012c).
ReflectingevolvingC++codingstandards(seeMeyers2005),Eddelbuetteland
Franc¸oisstartedasignificantredesignofthecodebasein2009.Thisaddednumer-
ousnewfeatures,manyofwhicharedescribedinthepackageviadifferentvignettes.
This redesigned version of Rcpp (Eddelbuettel and Franc¸ois 2012a) has become
widely used with over ninety CRAN packages depending on it as of November
2012.Itisalsotheversiondescribedinthisbook.
Rcppcontinuestobeunderactivedevelopment,andextensionsarebeingadded.
Thecontentdescribedhereshallremainvalidandsupported.
RelatedWork
IntegrationofC++andRhasbeenaddressedbyseveralauthors;theearliestpub-
lishedreferenceisprobablyBatesandDebRoy(2001).The“WritingRExtensions”
manual(RDevelopmentCoreTeam2012d)hasalsobeenmentioningC++andR
integrationsince aroundthattime. AnunpublishedpaperbyJava etal.(2007)ex-
pressesseveralideasthatareclosetosomeofourapproaches,thoughnotyetfully
fleshedout.TheRservepackage(Urbanek2003,2012)actsasa socketserverfor
R.Ontheserverside,RservetranslatesRdatastructuresintoabinaryserialization
formatandusesTCP/IPfortransfer.Ontheclientside,objectsarereconstructedas
instancesofJavaorC++classesthatemulatethestructureofRobjects.
The packages rcppbind (Liang 2008), RAbstraction (Armstrong 2009a), and
RObjects(Armstrong2009b)areallimplementedusingC++templates.Noneof
them have matured to the point of a CRAN release. CXXR (Runnalls 2009) ap-
proachesthistopicfromtheotherdirection:itsaimistocompletelyrefactorR on
a strongerC++ foundation.CXXR is thereforeconcernedwith all aspectsof the
R interpreter, read-eval-print loop (REPL), and threading; object interchange be-
Preface ix
tweenRandC++isbutonepart.AsimilarapproachisdiscussedbyTempleLang
(2009a)whosuggestsmakinglow-levelinternalsextensiblebypackagedevelopers
inordertofacilitateextendingR.TempleLang(2009b),usingcompileroutputfor
referencesonthecodeinordertoaddbindingsandwrappers,offersaslightlydif-
ferentangle.Lastly,therdyncallpackage(Adler2012)providesa directinterface
fromRintoClanguageAPIs.ThiscanbeofinterestifRprogrammerswanttoac-
cesslower-levelprogramminginterfacesdirectly.However,itdoesnotaimforthe
same object-level interchange that is possible via C++ interfaces, and which we
focusonwithRcpp.
TypographicConvention
The typesetting follows the usage exemplified both by the publisher, and by the
JournalofStatisticalSoftware.Weuse
• Sans-serifforprogramminglanguagesuchasRorC++
• Boldfacefor(CRANorother)softwarepackagessuchasRcpporinline
• Courierforshortsegmentsofcodeorvariablessuchasx <- y + z
Wemakeuseofaspecificenvironmentfortheshortpiecesofsourcecodeinter-
wovenwiththemaintext.
RiverForest,IL,USA DirkEddelbuettel
Description:Rcpp is the glue that binds the power and versatility of R with the speed and efficiency of C++. With Rcpp, the transfer of data between R and C++ is nearly seamless, and high-performance statistical computing is finally accessible to most R users. Rcpp should be part of every statistician's toolbox