{"id":95,"date":"2016-06-03T21:19:45","date_gmt":"2016-06-03T21:19:45","guid":{"rendered":"https:\/\/leedavies.dev\/?p=95"},"modified":"2016-06-03T21:19:45","modified_gmt":"2016-06-03T21:19:45","slug":"creating-an-r-package-with-native-code-using-rcpp","status":"publish","type":"post","link":"https:\/\/leedavies.dev\/index.php\/2016\/06\/03\/creating-an-r-package-with-native-code-using-rcpp\/","title":{"rendered":"Creating an R Package with Native Code using Rcpp."},"content":{"rendered":"<p>There does not appear to be a good set of instructions on getting a new custom R Package (utilizing Rcpp to call C++ from R) so given that I have gone through the pain of configuring this for a project I am working on I decided to write down some instructions on what I did.<\/p>\n<p><strong>Initial Set-up<\/strong><\/p>\n<p>I have the following pieces of software installed.<\/p>\n<ul>\n<li>R Studio &#8211; 0.99.902<\/li>\n<li>R Version &#8211; 3.3.0<\/li>\n<li>R Tools &#8211; 3.3.0.1959<\/li>\n<\/ul>\n<p>As getting R and R Studio installed and configured are already covered by a number posts I won&#8217;t repeat those steps here (just make sure that you install R before you install R Studio).<\/p>\n<p>From within R Studio install the devtools package.<\/p>\n<p><a href=\"https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/DevTools.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-96\" src=\"https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/DevTools-300x220.png\" alt=\"DevTools\" width=\"300\" height=\"220\" srcset=\"https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/DevTools-300x220.png 300w, https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/DevTools-368x270.png 368w, https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/DevTools.png 390w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><\/p>\n<p>From the console you can use the following command<\/p>\n<p><em>install.packages(&#8220;devtools&#8221;)<\/em><\/p>\n<p>Next install the Rcpp package<\/p>\n<p><a href=\"https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/RCpp.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-99\" src=\"https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/RCpp-300x221.png\" alt=\"RCpp\" width=\"300\" height=\"221\" srcset=\"https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/RCpp-300x221.png 300w, https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/RCpp-367x270.png 367w, https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/RCpp.png 383w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><\/p>\n<p>From the console you can use the following command:<\/p>\n<p><em>install.packages(&#8220;Rcpp&#8221;)<\/em><\/p>\n<p>Next create the package that will contain our native library and the R code to call the library.<\/p>\n<p><strong>Creating and build the package.<\/strong><\/p>\n<p>To create the package from R Studio menu New -&gt; New Project<\/p>\n<p>For this project I am going to use a new directory so select that option in the dialog.<\/p>\n<p>Select R Package for the project type (this will generate the skeleton R Package project for you).<\/p>\n<p><a href=\"https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/Create_R_Package.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-100\" src=\"https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/Create_R_Package-300x213.png\" alt=\"Create_R_Package\" width=\"300\" height=\"213\" srcset=\"https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/Create_R_Package-300x213.png 300w, https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/Create_R_Package-381x270.png 381w, https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/Create_R_Package.png 530w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><\/p>\n<p>Set the package name and then provide a location where the sub directories will be created. For my example my package will be called testprojone and I am created this package in the directory &#8220;D:\/AllData&#8221;<\/p>\n<p>RStudio will generate a number of files and directories under &#8220;D:\\AllData\\testprojone&#8221;.<\/p>\n<p>Now we have the package we can test that this works by calling the hello function (which is automatically created), but first we need to build and register the package.<\/p>\n<p>From the RStudio use the following command<\/p>\n<p>Build -&gt; Build and Reload (Ctrl +Shift +B)<\/p>\n<p>In the Build output you should see the following output<\/p>\n<p style=\"margin: 0in;font-family: 'Lucida Console';font-size: 10.0pt;color: blue\">==&gt; Rcmd.exe INSTALL &#8211;no-multiarch &#8211;with-keep.source testprojone<\/p>\n<p style=\"margin: 0in;font-family: 'Lucida Console';font-size: 10.0pt\">* installing to library &#8216;D:\/Program Files\/R\/R-3.3.0\/library&#8217;<br \/>\n* installing *source* package &#8216;testprojone&#8217; &#8230;<br \/>\n** R<br \/>\n** preparing package for lazy loading<br \/>\n** help<br \/>\n*** installing help indices<br \/>\n** building package indices<br \/>\n** testing if installed package can be loaded<br \/>\n* DONE (testprojone)<\/p>\n<p>In the console the package should be (re)loaded.<\/p>\n<p><em>library(testprojone)<\/em><\/p>\n<p>Now with the package loaded we can run the hello function to make sure that everything is working.<\/p>\n<blockquote><p><em>&gt;hello() <\/em><\/p><\/blockquote>\n<p><em>[1] &#8220;Hello, world!&#8221;<\/em><\/p>\n<p><strong>Create and compiling the C++ code.<\/strong><\/p>\n<p>Congratulations your package is loading however we want to implement our code in C++ rather than R itself so lets add a new C++ file.<\/p>\n<p>File -&gt; New File -&gt; C++<\/p>\n<p>As this point you may be prompted to install\/load additional tools into R Studio, in which case select the Yes option.<\/p>\n<p>By default the file contains a test function called timesTwo with the following code.<\/p>\n<p><code>\/\/ [[Rcpp::export]]<br \/>\nNumericVector timesTwo(NumericVector x)<br \/>\n{ return x * 2;}<\/code><\/p>\n<p>Before we rebuild our package we first save the new C++ file.<\/p>\n<p>Create a new directory called &#8220;src&#8221; under the package root directory and save the untitled file as SimpleExample.cpp under the &#8220;src&#8221; directory.<\/p>\n<p>The package structure should now appear as follows.<\/p>\n<p style=\"margin: 0in;font-family: 'Lucida Console';font-size: 10.0pt\">\u00a0<a href=\"https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/Files_One.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-medium wp-image-97\" src=\"https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/Files_One-300x190.png\" alt=\"Files_One\" width=\"300\" height=\"190\" srcset=\"https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/Files_One-300x190.png 300w, https:\/\/leedavies.dev\/wp-content\/uploads\/2016\/06\/Files_One.png 416w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><\/p>\n<p>Open the DESCRIPTION file (in the root of the package) and add the following two lines.<\/p>\n<p><em>LinkingTo: Rcpp<\/em><br \/>\n<em>Imports: Rcpp<\/em><\/p>\n<p>The contents of the file should now look like this.<\/p>\n<p><em>Package: testprojone<\/em><br \/>\n<em>Type: Package<\/em><br \/>\n<em>Title: What the Package Does (Title Case)<\/em><br \/>\n<em>Version: 0.1.0<\/em><br \/>\n<em>Author: Who wrote it<\/em><br \/>\n<em>Maintainer: Who to complain to &lt;yourfault@somewhere.net&gt;<\/em><br \/>\n<em>Description: More about what it does (maybe more than one line)<\/em><br \/>\n<em>License: What license is it under?<\/em><br \/>\n<em>LazyData: TRUE<\/em><br \/>\n<em>LinkingTo: Rcpp<\/em><br \/>\n<em>Imports: Rcpp<\/em><\/p>\n<p>As this is an example I am going to leave the default values for the rest of the parameters in this file.<\/p>\n<p>When you recompile you should see a testprojone.dll generated with the same name as the package. This contains the compiled C++ function from the SimpleExample.cpp file we saved earlier.<\/p>\n<p>Now include information for this dll in the NAMESPACE file (in the root of the package) by adding the following lines.<\/p>\n<p><em>useDynLib(&#8220;testprojone&#8221;)<\/em><br \/>\n<em>importFrom(Rcpp, sourceCpp)<\/em><\/p>\n<p>The contents of the file should now look like this:<\/p>\n<p><em>useDynLib(&#8220;testprojone&#8221;)<\/em><br \/>\n<em>importFrom(Rcpp, sourceCpp)<\/em><br \/>\n<em>exportPattern(&#8220;^[[:alpha:]]+&#8221;)<\/em><\/p>\n<p>When you &#8220;Build and Reload&#8221; you should see 2 new files generated RcppExports.cpp created under the \/src directory and RcppExports.R under the \/R directory, if you don&#8217;t see these files look in the &#8220;Build&#8221; window for any errors. If you edit either of these files manually the next time you rebuild your changes will be replaced.<\/p>\n<p>RcppExports.cpp contains the functions that are used by the R code to map to the C++ function.<\/p>\n<p><code>\/\/ timesTwo<br \/>\nNumericVector timesTwo(NumericVector x);<br \/>\nRcppExport SEXP testprojone_timesTwo(SEXP xSEXP) {<br \/>\nBEGIN_RCPP<br \/>\nRcpp::RObject __result;<br \/>\nRcpp::RNGScope __rngScope;<br \/>\nRcpp::traits::input_parameter&lt; NumericVector &gt;::type x(xSEXP);<br \/>\n__result = Rcpp::wrap(timesTwo(x));<br \/>\nreturn __result;<br \/>\nEND_RCPP<br \/>\n}<\/code><\/p>\n<p>RcppExports.R contains the R function to call the C++ function using the &#8220;Call&#8221; function specifying the function to call, the package containing the function and any parameters passed.<\/p>\n<p><code>timesTwo &lt;- function(x) {<br \/>\n.Call('testprojone_timesTwo', PACKAGE = 'testprojone', x)<br \/>\n}<\/code><\/p>\n<p>If everything is configured correctly from the R Console window you should be able to run the timesTwo function.<\/p>\n<blockquote><p>&gt; library(testprojone)<\/p>\n<p>&gt; timesTwo(100)<\/p><\/blockquote>\n<p>[1] 200<\/p>\n<p><strong>Troubleshooting<\/strong><\/p>\n<p>If you installed Rtools in a different directory other than C:\\Rtools then in the &#8220;Build&#8221; window when R Studio compiles the C++ code you will get an error that directory &#8220;C:\\Rtools&#8221; cannot be found, in which case set the following environment variable (with your path to Rtools) from the Rstudio Console using the following command<\/p>\n<p>Sys.setenv(BINPREF = &#8220;D:\/Rtools\/mingw_64\/bin\/&#8221;)<\/p>\n<p>Then &#8220;Build and Reload&#8221; the package.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>There does not appear to be a good set of instructions on getting a new custom R Package (utilizing Rcpp to call C++ from R) so given that I have gone through the pain of configuring this for a project I am working on I decided to write down some instructions on what I did. Initial Set-up I have the following pieces of software installed. R Studio &#8211; 0.99.902 R Version &#8211; 3.3.0 R Tools &#8211; 3.3.0.1959 As getting R&#8230;<\/p>\n<p class=\"read-more\"><a class=\"btn btn-default\" href=\"https:\/\/leedavies.dev\/index.php\/2016\/06\/03\/creating-an-r-package-with-native-code-using-rcpp\/\"> Read More<span class=\"screen-reader-text\">  Read More<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[18],"tags":[],"class_list":["post-95","post","type-post","status-publish","format-standard","hentry","category-r"],"_links":{"self":[{"href":"https:\/\/leedavies.dev\/index.php\/wp-json\/wp\/v2\/posts\/95","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/leedavies.dev\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/leedavies.dev\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/leedavies.dev\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/leedavies.dev\/index.php\/wp-json\/wp\/v2\/comments?post=95"}],"version-history":[{"count":16,"href":"https:\/\/leedavies.dev\/index.php\/wp-json\/wp\/v2\/posts\/95\/revisions"}],"predecessor-version":[{"id":116,"href":"https:\/\/leedavies.dev\/index.php\/wp-json\/wp\/v2\/posts\/95\/revisions\/116"}],"wp:attachment":[{"href":"https:\/\/leedavies.dev\/index.php\/wp-json\/wp\/v2\/media?parent=95"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/leedavies.dev\/index.php\/wp-json\/wp\/v2\/categories?post=95"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/leedavies.dev\/index.php\/wp-json\/wp\/v2\/tags?post=95"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}