Home

How To Make an R Package Based on C++ And Manage It With R

image

Contents

1. Note that we must manually deallocate memory with the RMat class since its destructor doesn t do this This is in anticipation of using the RMat class with R vMat1 DeallocateMemory vMat2 DeallocateMemory vMat3 DeallocateMemory vMat4 DeallocateMemory vMat5 DeallocateMemory vMat6 DeallocateMemory if COMPILE_WITH_R printf nUsing R math library to compute R_pow 2 3 g n R_pow 2 3 endif system PAUSE return EXIT_SUCCESS return 0 21 Chapter 4 Make a Shared Dynamically Linked Library As an intermediate step between building a stand alone program that exercises the C code chapter 3 and making an R package chapter 5 I think it s very useful to first create a dynamically linked library and debug it because the Edit Build Run debugging cycle is faster Once it s debugged you can then proceed to make the full blown R package For this chapter and the next I have drawn heavily on Alan Lenarcic s tutorial 5 4 1 RInterface cc Below is the code for C C functions that will interface the RMat class with R Cut and paste this source code into a plain text file named RInterface cc For your convenience this source code is included in the ZIP file given previously http howtomakeanrpackage pbworks com f Code zip In the C C interface code below note the following e the C wrapper function CWrapper does not contain any instantiations
2. Open cmd Ca gR r Figure 2 5 The Run dialog box C WINDOWS system3 2 cmd exe icrosoft Windows XP Version 5 1 2608 lt C gt Copyright 1985 2801 Microsoft Corp NDocuments and Settings admin gt _ Figure 2 6 DOS prompt 11 2 1 7 Dev C or NotePad optional In his tutorial A Lenarcic suggested obtaining a general coding text editing program for C code He suggested the Crimson Editor URL http crimsoneditor com english download html but qualified his suggestion with the observation that this editor at least that particular version didn t eliminate CRLF returns to his satisfaction I believe that the Convert to UNIX Format fea ture of Notepad URL http notepad plus plus org may do the trick Also Notepad recognizes multiple standard programming languages including C and is able to show computer code in context sensitive colors e g comments in green reserved symbols in purple and preprocessor macros in red For this tutorial we ll use gcc the Gnu compiler that comes with R Tools this will be fine for the example we ll be dealing with For larger scale programming efforts you might consider using a full fledged integrated de velopment environment IDE such as Microsoft Visual Studio For a freely available option consider Dev C URL http www bloodshed net dev Note that Dev C uses the MinGW port of the Gnu compiler I think that this means that if you
3. this i j 0 0 T return true Deallocate memory void RMat DeallocateMemory 1 if mValues 0 1 delete mValues mValues 0 T 3 3 tost HR Mat cc include lt cstdlib gt include lt iostream gt include RMat h if COMPILE_WITH_R include lt Rmath h gt endif using namespace std int main int argc char argv Test element access set value get value RMat vMat1 2 3 int vCount 0 for int i 1 i lt 2 i for int j 1 j lt 3 j vMati i j vCount Y T vMati Print vMati Nn cout lt lt endl lt lt vMat1 2 2 lt lt vMat1 2 2 lt lt endl Test special constructor for pre allocated memory We ll use this when passing data from R to C vMat2 should be a 2 by 3 matrix containing values between 3 and 8 double vValues vValues new double 6 for int i 0 i lt 6 i vValues i i 3 RMat vMat2 vValues 2 3 vMat2 Print nvMat2 n Test assignment RMat vMat3 vMat3 vMat1 vMat3 Print nvMat3 n Test copy constructor 20 RMat vMat4 vMat3 vMat4 Print nvMat4 An Test transpose RMat vMat5 vMat4 Transpose vMat5 Print nvMat5 n Test matrix multiplication RMat vMat6 vMati vMat5 vMat6 Print nvMat6 n Test setting all matrix elements to a scalar value vMat6 0 0 vMat6 Print nNow vMat6 n
4. Figure B 4 The Dev C4 4 Include Options dialog box 63
5. RMat RMat Transpose RMat vTranspose mNumCols mNumRows for int i 1 i lt mNumRows i for int j 1 j lt mNumCols j 1 vTranspose j i this i j T return vTranspose Print 1 void RMat Print for int i 1 i lt mNumRows i for int j 1 j lt mNumCols j 1 cout lt lt this i j lt lt cout lt lt endl T T Print 2 void RMat Print const char vString cout lt lt vString Print 18 if COMPILE_WITH_R RPrint 1 void RMat RPrint 1 for int i 1 i mNumRows i 1 for int j 1 j lt mNumCols j 1 Rprintf g this i j Rprintf n R FlushConsole R ProcessEvents T RPrint 2 void RMat RPrint const char vString 1 Rprintf s vString RPrint endif Get number of rows int RMat NumRows const 1 return mNumRows Get number of columns int RMat NumCols const return mNumCols Allocate memory Initialize all entries to 0 bool RMat AllocateMemory int x int y DeallocateMemory try mValues new double x y T catch I cerr lt lt Rmat AllocateMemory 0 unable to allocate memory for lt lt x lt lt by lt lt y lt lt matrix lt lt endl return false mNumRows x mNumCols y for int i 1 i lt mNumRows i 1 for int j 1 j lt mNumCols j f 19
6. 49 Checkout Figure 6 14 TortoiseSVN Checkout Dialog Box 50 Open Explore Scan using Spybot Search amp Destroy Search 7 Zip gt Sharing and Security SVN Update SVN Commit H TortoiseSVN gt Scan with AVG Free Scan with Malwarebytes Anti Malware W scan Send To K CUL Copy Create Shortcut Delete Rename Properties Figure 6 15 TortoiseSVN Context Menu With Commit Option 51 Commit C Rpackages ptinpoly Commit to svn ssh imaisog svn r forge r project org svnroot ptinpoly Message Recent messages Changes made double click on file for diff Extension Textstatus Propertystatus Lock pkg data added E pka data faces rda rda added E pkg data queries rda rda added E pkg data triMesh rda rda added E pkg data verts rda rda added S nla MECCDOTOTTAONI sdded Show unversioned files Select deselect all 3le fra v 23 files selected 23 files total NENNE z Figure 6 16 TortoiseSVN Commit Dialog Box 52 To install directly from CRAN type e g install packages your R package repos http cran r project org Later if you discover that your R package has a bug check out the files from R Forge as described in section 6 4 This time the check out folder will contain local copies of the R package files stored in R Forge Modify the files in the check out folder to fix the bug after making your edits yo
7. Code To R Libraries Here I show how to link the stand alone example C code to the R libraries but using Dev C rather than gcc The process is pretty much the same as for gcc except that specifying library and include directories is done through a graphical user interface rather than on the command line Again be sure that the COMPILE WITH R macro is set to 1 rather than 0 see section 4 2 1 2 In Dev C create a new Console Application project Add the three files testRMat cc RMat cc and RMat h to the project In Dev C select Project gt Project Options This should bring up the Project Options dialog box as shown in Figure B 1 In the Project Options dialog box click on the Parameters tab In the white pane under Linker type in the text 1R The second character is a small L not a numeral 1 This is to tell the linker to link in the R library at build time This is illustrated in Figure B 2 In the Project Options dialog box click on the Directories tab This should bring up the Directories sub dialog box as shown in Figure B 3 The Library Directories sub tab should be selected by default Add the R bin folder by clicking on the little square button with an icon of a folder tree structure browsing to the R bin folder then clicking on the Add button you must click on the Add button 58 Still in the Directories sub dialog box click on the Include Directories sub tab Add the R inclu
8. aBey awoy yaloig se 1v 3 Iqnd he joefoud siy 10 e qejrene spes SSY Jo ISI WSIA Ayo y 10 SJNSNEIS yaloid mai 0 lnu o21aq Away LTZ ST70 0LOZ Paasi ay sonsneis gq jeneds sjapoyy jediydesy soneuuojurouieu 3Ido e Y 2 2 eBDenBue Burwwesboig XISOd smopum SOIN ueis s Buneiedo usijbu3 eBenBue7 jeunjey 149 asuaar 3 Iqnd jejeuec NNO esuear doysaq siesp pug eaueipny pepueju 9999 wol og 1s nb ti smoputAA SIN Z uIAA 1u uuuouu3 13470 paseg 1xe ejosuo JUSBWUOINUJ siaquiayy man e18g p SNJEIS uaudojanaq e Bosieyy asor suiupy 17910614 uonejuesaeidai sa3ijie sea2ej snsJa 54I0 Q 8814 UOJpayAjod ay Buluu p jo s em omy usamyjaq oju sadojanag yie uo2Jejul 01 suomoun se jjam se uojpeu AJod p so 3 e uiyym peurejuoo SI juod e jeujeuM sa 01 UONDUNJ e s piA01d yoaloud siu p sabeyoed y WOS ss ianov umupy Kieuiuns uoJpeu jod ur jueuiurejuoo Julod 1011591 9211 j2efoud eDed AN 9uioH aunooov W no 507 IDE 26 10 CPP youeas paoueApy palod amus 34 owas syeuyooqu2gO J lt wO xuae3 7 vom T swan i aiae D ces RB aw uwE xd emia Iue oH LA eug LA szuasno 7 v A Aodund si efoid B1032efoud rs640 1 sd u B E uo quod oj ysa 50 O f tory link in bottom left i Figure 6 5 R Forge PtInPoly Project Page Note SCM Repos corner A G PulTY Key Generator File Key
9. 12 2 2 2 PuTTY PuTTY is a free SSH Telnet and Rlogin client for 32 bit Windows systems We need the PuTTY distribution for its public key encryption software since R Forge uses this par ticular encryption system for security Download the PuTTY distribution from this URL http www chiark greenend org uk sgtatham putty After downloading and unpack ing it you should see a few files including two named puttygen exe and pageant exe we will be using these two programs in section 6 3 and section 6 4 For further information on public key encryption in the context of PuTTY see http tartarus org simon putty snapshots htmldoc Chapter8 html pubkey 13 Chapter 3 Example C Code A Simple Matrix Class In the three sections of this chapter I list the code listing for example C code that we ll use in this tutorial e RMat h header file declaring the interface to a simple C matrix class named RMat which we ll interface with an R matrix e RMat cpp C code defining the member functions of the RMat class This is not the most efficient implementation for a C linear algebra library but it will suffice for this tutorial For a discussion of efficient scientific programming in C see e g 10 and 11 see also Chapter 5 of R Davies documentation for his NewMat C linear algebra library URL http www robertnz net nm11 htm design e testRMat cc C code for a driver program defining a main function which
10. I C RTools MinGW include I C Program Files R R 2 10 1 include You ll note that each invocation of gcc has two I arguments These two arguments tell the compiler where to find the include files for standard C functions and for the R functions Of course your installation of RTools and for R may differ from mine so you ll need to modify the folder paths accordingly The code in RInterface cc is not involved since we re not accessing the C code through R here Then link the two object files with the R library as follows gcc testRMat o RMat o o testRMat exe L C RTools MinGW lib L C Program Files R R 2 10 1 bin 1R lstdc 56 Here the two L arguments tell the compiler where to find the binary libraries for standard C functions and for the R functions Again you ll need to modify the folder paths ac cording to your own computer system Then run the the newly built executable by typing testRMat exe at the DOS prompt You should see the same output that you saw in chapter 3 But in addition you should see this line at the end Using R math library to compute R pow 2 3 8 This demonstrates that the C code successfully accessed the R math function R pow As mentioned earlier see Chapter 6 of 8 for more on the R API URL http cran r project org doc manuals R exts htmliThe R API that chap ter lists many R functions that you might find useful 57 Appendix B Dev C Link Stand Alone Example C
11. TeX optional This is optional it is needed to create pdf help files However it is possible to build a working R package without pdf help files 3 A Lenarcic s tutorial seemed to imply that MiK TeX 6 should be installed before RTools so I have listed it here first Go to the MiKTeX website URL http www miktex org and download the latest version of MiK TeX After you ve downloaded the MiKTeX installer run it perhaps by double clicking on its icon or perhaps by selecting Open in your downloader 2 1 4 Microsoft HTML Help Workshop optional As with MikTeX HTML Help Workshop is optional It is needed to create chm help files However it is possible to build a working R package without chm help files 3 Download it from this URL http www microsoft com downloads details aspx FamilyID 00535334 c8a6 452f 9aa0 d597d16580ccdisplaylang en or do a web search for HTMLHelp exe 2 1 5 perl optional As mentioned above subsection 2 1 2 the latest version of RTools should come with perl However if you try to run remd check section 5 2 and section 5 5 and get an error message that the command perl is not found it means that you re missing perl and that you need to download and install it If so you can obtain it from here http www activestate com Products activeperl 2 1 6 Set Up Your Windows Path Variable The Path variable is a list of folders that are searched when a program is invoked at the DOS prompt o
12. To check the folder back in to R Forge go into the parent folder of the check out folder created in Right mouse button click on the icon for the check out folder which should pop up a context menu that include TortoiseS V N options see From the TortoiseSVN context menu select SVN Commit This should pop up the Tortoise SVN Commit dialog box as seen in Click on the OK button to upload the modified files back to the repository on R Forge After checking the files back into the R Forge repository the red exlamation point on the icon of the check out folder will be 47 Select Private Key File Look in e R Forge 4 E examplePrivate ppk 2 putty private key ppk My Recent Documents 3 File name Files of type PuTTY Private Key Files ppk Open as read only Figure 6 12 Pageant Add Key Dialog Box changed to a green check sign this is TortoiseSVN s way of indicating that the check out folder has been committed to the respository Now you must wait R Forge performs nightly builds and if an error is found a log should be generated You can see the schedule for nightly builds by logging in to your R Forge ac count and going to the Contributed R Packages page for your R project see Figure 6 17 Note the blurb that states All packages are built checked according to this schedule this sentence provides a link to the schedule for the nightly builds After the night
13. an R Package for Windows With Native Routines in Fortran 95 Technical report Pennsylvania State University 2008 The R Development Core Team Writing R Extensions v 2 8 0 Technical report The R Project 2008 S Theufl and A Zeileis Collaborative Software Development Using R Forge The R Journal 1 1 9 14 2009 T Veldhuizen Linear Algebra with C4 4 Template Metaprograms Dr Dobb s Journal 21 8 38 40 42 44 1996 T Veldhuizen Techniques for Scientific C Technical report Indiana University 2000 95 Appendix A MinGW gcc Link Stand Alone Example C Code To R Libraries Suppose that for some reason you want to compile the stand alone C code given in chap ter 3 but with the R libraries linked in as they are in the R package In this appendix I show how this might be done using gcc This demonstrates the possibility of invoking R functions e g math functions outside of R in a stand alone C program Edit the file RMat h so that the macro COMPILE WITH R is set to 1 rather than 0 see section 4 2 In addition to enabling lines to access the R libraries in the files RMat h and RMat cc this will also enable a line in the driver program test RMat cc that calls an R math function Then build the two o object files RMat o and testRMat o with commands that look like this gcc c RMat cc o RMat o I C RTools MinGW include I C Program Files R R 2 10 1 include gcc c testRMat cc o testRMat o
14. could have submitted the Linux build to CRAN and CRAN would have generated the MacOS build for me But I didn t think of this at the time Then during my poster presentation at JSM 2009 Tom Lumley suggested that we try R Forge The way it was described to us you upload the raw source material for your R package to R Forge and R Forge automatically makes Linux Windows and MacOS builds for you Learning how to use R Forge took me a little longer than it really should have Part of the problem was that there seemed to be two other pieces of software that I had to learn about Subversion which is the version control system that R Forge uses and TortoiseSVN which provides a nice graphical user interface GUI to Subversion In essence I had an extra degree of freedom that I was needlessly worrying about I finally figured out that I needed to cone down only on learning TortoiseSVN and only on two basic operations check out and commit Once I got TortoiseSVN under my belt I was then able to use R Forge with ease And once I was able to use R Forge I was able to generate builds of the ptinpoly package for all three platforms Linux Windows and MacOS If you re interested the method on which the ptinpoly package is based has been published as a paper 6 Since then I have found two other tutorials on building R packages that have helped im prove my understanding of the process a tutorial by Schafer 7 in which he describes how
15. e eu NOA Essi apes Aw susu passen sev pens ipe peuemy sene pavbssv yealoig 18151683 a2ueuajulep 3uno22y s oN Heq eBeg jeuosiag W 92811 j2efo1d eDeg AW euioH OL duunr pino 6 J ansees 9DJO ED syeunjoog RO J lt Dan S mune 7 vpn I sven 16 wswo O as av FE xus g gw 16 geuekon pA pews pA sznuuosnp TJ Y ox Au B10 pafod 13610j 4 sdny B D gt S afea gesa Bean C Figure 6 2 R Forge just after logging in Note links Account Maintenance and Regis 38 ter Project button My Page and tab Projects uoniugep e2inogued ay ui ejqneduio2 s esuaai Jeu 338u2 0 peau m aM eauis Joalosd y ns 104 UOISIDap e exeuu 01 euin euonippe aye Aew y ospy pe oudde aq jou Aew sesueai Jayjo Jey ezijeag esuaoi jno jo uonduosep e yym Buoje uongue dx ue apuold aseajd Jayjo payoajas nod J 149 ssusor1 2 Jang 82039 NNO 2su22n usibu3 ui uapum aq jsnui 3 32afo1d ino jo uogduosap or qnd e se pasn ag jou jim uogduosap siu Aem papuazu y ur sa2rAjes aqu Buisn ase nof jeu aunsue OJ 13je pue 36104 4 uo Bunsou sjoafoid 4nok jo uogaafa1 10 jeaosdde aig 104 SISEG aqu aq jw uogduosap siuj sn oj uejd nok Kem quarum u pue sa24nosaJ abs04 y JEYM pue j2afoud Inok jo uondiuos p qe1nooe pajrejap apinoid aseajq uonezueuruns Puy 23sodang Pod euieN N4 nun pE Qr E 1deoxe suonpiasai WEIS
16. ou seu PUB aAndiosep si BWEN IIn3 SYL Plod o jo Sweu eu Burgroads ui yes pinous noA aweu yny paloig T m uojepueui ae mojaq spay IIV amp 3ep anisuayaidwod pue ejejduio2 apnosd pue Ajjnyased mojaq suonduosap peas aseajq U oqe uoneuuojul JISEG Ul jy pinoys no uone1si6 yoalosd 104 Ajdde og 9211 2elo1d f abed N SWOH A vo dunropino 5 J raet CELLS D4O CD I sueunooq 240 C lt om sa 7 vom I sau i wisn 9 cs ow uB ows ende peueko LA ews tal aso T Y A dyd ojundafoid 1315634 640 ppafo4d 1 3610J 4 sdnu amp O FIA x uoneuuojulj loid 35104 Figure 6 3 R Forge Register Project Page 39 Ansen _ NISNODSIM VNN3IA eB104 9 uolsng 0 N 0 Syuey l ynejeg uospayAjod ur JUSLUUIEJUOJ JUIOA 104 159 8 joefoug 18151683 e2ueuejurejy 3uno22y s oN Merg eBeg jeuosiag W 9911 PAd ebed AW 9uioH ie 26101 8 syueunjooq 20 C lt Dam 3 me 7 ven T sven 16 xuswo O as aw amp Fm revs pews i Ieue amp oH LA pew pA szuosno 7 ba Au B10 pafod 13610j 4 sdn B D gt z TETS 04 sed jeuosiad 282048 C Figure 6 4 R Forge My Projects After your project is successfully registered a link for the project will appear under the Projects tab 40 0 SYUEYL sppe cz seiepdn 7 NAS Auoysodey WOS s si Bunreui oyqnd p sjs buen pg Tl
17. public private key pair Load an existing private key file Save the generated key Parameters Type of key to generate Number of bits in a generated key Figure 6 7 PuTTY Key Generator in the process of generating public and private keys Windows browser and select File gt TortoiseSVN Checkout This will pop up the TortoiseSVN Checkout dialog box as seen in Figure 6 14 This dialog box will create a new folder which will contain the checked out files You must now type in a name to be given to this check out folder 7 l d suggest giving the check out folder a name that indicates the project and the current date and or some sort of version number to distinguish it from check outs that you may do in the future E g if you were checking out a project named multmat for the second time on the date December 17 2010 you might name the folder something like multmat B 121710 This should create a check out folder with the name you indicated The check out folder s icon will look slightly different from the usual folder icon It will have a small red exclamation point overlaid on top which is TortoiseSVN s way of indicating a check out folder that hasn t been committed checked in yet 43 Pul TY Key Generator Figure 6 8 PuTTY Key Generator showing keys that were generated The newly generated public key is the selected text highlighted in blue 44 Im ws NISNOOSIM VNN3IA E A e8
18. sis jeue 104 sjoo 11 997 sjapow sj2aye pexiyy peu 9 0709 aseysy ang Spjal4 uiopue 104 poourjexr aysodwod se zg SONSHEIS 1sngoy 21669 aseqysnqou 8 paaiquAs 2 pg sisAjeue yomjau er20s BUAISH 6 9 SI PON ejqeueA lu le1 jo sis jeuy enef L 28 DbojoupA pHo23 Z 88 wwHy 68 y u Buiujg 1 auiyseyy 9 06 syebpib seg Lg sonsne1s 32noldui sy 1snqoy 15vqos 6 T6 seuienxe ejeueannui jeuonipuo L YG SUOIINGUISIP 104 sesse PS NSIP 6 uoneJbaju 9 pue y ss luue s dd 96 eqep jeneds Jesel 9 9776 0 eBessaui e Duipuas Aq p ule1qo eq ued sjuudyo peusijqnd uaaq seu abeyoed ayy yum Bueap Jaded v wedos gZ Z LO ZL 0LOZ uregpiugogs uegseqes 1edeg payejay sman 159JET ays ayy olua pue syueuy B1io 1o lo1iq H B103 x 0 pewa ue 91M JO Wea a io Y ay 01 jsenbai uoddns e pWwqns ued no dieu peau Jo swajqoid Aue e2ueuedxe nok j uogejuewn2op e21u428j p lie q ipd enue sJasN e uogeyio Buo3 u 191440 Ados e90 pd qq 5zo 328 Cozd as reuznoC daau TYN 6007 Aew vL 6 L Jeunor y ay e6104 Y usn juawdojanap eie yos enneloqe o siejiez WIYIY pue gneu uejejs uononponu POUS e uonejueuin2oq uonejueuino2op 84 385 slie1 p 104 sainjea eulos 0 ssa22e pejui a eu Ajuo jIM yng uonensiba Jnoyym ays ayy asmolg osje Aew no asinoo JO 12efo1d 1no 18151681 Aew nok Ba ayo 01 aney am HIE u n a
19. the project see Figure 6 5 6 3 Configure Your Security Configure your security with the following steps 1 Invoke puttygen exe by double clicking on its icon this should pop up the PuTTY key generator as shown in Figure 6 6 2 Leave SSH 2 RSA selected and click on Generate See Figure 6 7 and Figure 6 8 The newly generated public key is the selected text highlighted in blue in Figure 6 8 3 Go to the Account Maintenance page in R Forge see Figure 6 9 4 At the bottom of the Account Maintenance page you should see a link labeled Edit Keys Click on this link 5 You should now see a web page that looks like Figure 6 10 Note the large entry box towards the bottom labeled Authorized keys Copy and paste your public key Figure 6 8 into the entry field 6 Then wait for at least an hour For more information on using puttygen see this page This corresponds to copying and pasting your public key into R Forge 6 4 Check Out Files from R Forge To check out files from the R Forge repository perform the following steps 1 Invoke pageant exe by double clicking on its icon pageant exe will appear as a new icon in your system tray usually found in the bottom right corner of your computer desk top see Figure 6 11 36 S Seualajaid Jasn Wea 9 LL i Idx e1ep geli ADojoupA po23 6ZIL1 Inong 6Z L1 wedos 0 LL 103e2121u LO ZL syafoig palaysibay Aguasay aon Ingisnioiq 9 eyep oiuoueBida jo
20. we need to run a few commands at a DOS prompt to confirm that your Path variable has been properly set up 5 Bring up a new DOS shell by clicking 8 Environment Variables User variables for admin Variable Value PATH C Program Files SSH Communications S TEMP C Documents and Settings admin Local TMP C Documents and Settings admin Local Edit J Delete System variables Variable 1 Windows NT C Perllsitelbin C Perllbin C Program COM EXE BAT CMD VBS VBE JS PROCESSOR A x86 J eat L delete o gt Cancel Figure 2 2 The Environment Variables dialog box Edit System Variable Figure 2 3 The Edit System Variables dialog box Software folder Test Command R R bin rcmd help Gnu Compiler Rtools bin gcc help perl perl bin perl help MikTeX miktex bin tex help MinGW utilities Rtools bin grep help HTML Help Workshop HTML Help Workshop hhc help Table 2 1 Table of folders to list in the Path variable and commands to confirm El Document WordPad File Edit View Insert Format Help Deu SD BIC C Perl site bin C Perl bin C Program Files HTML Help Workshop C Program Files R R 2 10 1 bin C Rtools bin C Rtools MinGW C Rtools MinGWibin C DATA Program Files Perl bin C Program Files MiKTeX 2 7 miktex bin systemroot system32 systemroot systemroot system32 wb
21. where the problem arises I considered the possibilities that the problem arises because the folder path is too long e g perhaps not enough memory was allocated for the folder path or perhaps the path name should not contain spaces or other funny characters but these don t seem to be the problem If the remd check and rcmd build commands give you error messages about an unspecified package consider moving your project high up in the folder tree perhaps to C tmp such that the folder path is very short and doesn t contain any funny characters For details on the structure of R packages see Section 1 1 of 8 URL http cran r project org doc manuals R exts htmlitPackage structure 5 2 Run RCMD CHECK At this point it might be instructive to try running the remd check command To do this perform the following steps 1 Bring up a DOS prompt as before see subsection 2 1 6 Click on the Start button in the lower left corner of your desktop and select Start Programs gt Accessories gt Command Prompt Alternatively you can select Start gt Run and in the dialog box that pops up type cmd and then click on the OK button Either way a DOS prompt running in a window should pop up Figure 2 6 2 At this DOS prompt navigate to the parent folder containing the multmat folder you created in section 5 1 Again use the DOS commands chdir and dir to change and list folders exactly the same way you d use the cd an
22. 104 9 uon 0 N 0 SYUEYL Lue seu Laez shay upa s ay pezuouiny pareus HSS xoq 84S uopeuuoju juno22y Haus sBug amp i ui ajedidned o uasoyo a eu NOK 4 bed Jasn Jno uo ajqejie e si uoreuuojur S O sjaujo Ag pajeJ ag 0 se jja se euejuo e e es Duisn sjesn jaujo 378I o NOA swojjy sBunei saad u eyedionieg A oyeg mo7 sBuilieuu Ayunwwod euonippe anaosy C papuswwosay UBI se gou junoes sepnjour pue 21511 moj eA seyepdp eis 1noge ELF aae A Sa2uai19J8aJd eni Xv4 uoud ssauppy ss ippy Lippy jreur3 Bueuo np umol 6io 6 Guu uppy pewg S31v1S O3LINN uno 261028 away a euozeuij eDenBue se euieN 181 speurjoog 20 TJ lt Dun S unsa Z vpn U sven 16 ausw D os aw wp us dj pews 16 Ieue oH A pews pA szuosno 7 ve Mn unodde B10 pafoud 1 3b10j 4 sdn 8 O gt Note Edit Keys link at the Figure 6 9 Bottom of the Account Maintenance Page bottom under Shell Account Information 45 Ann NISNOOSIM VNN3IA eBioy uorsng Q0 N 20 SYUEYL Em Yeso 314 ON ai 250040 ajyAay e peojdn Aew noA Ajeaneureyy pajoedxe nof jeu si eji Jno ui S y jo jequunu au jeu juan Bugyuqns Jayy 2199 uaamjag jdsoxe syealg aul ou ale ajay ans ayey juepoduj s ay pezuouiny sAay Buueus uo uoneuuojur J uuni 104 uorjejueuun2op yss aui peay Z lo30101d qnd esi pi uss 10 qnd esp pi
23. Conversions Help Key No key Actions Generate a public private key pair Load an existing private key file Save the generated key Parameters Type of key to generate SSH 1 RSA SSH 2 RSA SSH 2 DSA Number of bits in a generated key n 024 Figure 6 6 PuTTY Key Generator Start Up Right mouse button click on this icon to pop up its context menu and select Add Key This pops up a browser window see Figure 6 12 Browse to the folder where you saved the ppk containing your private key from putty gen exe select the ppk file and then click on the Open button Because the private key is now loaded into pageant exe TortoiseSVN will be allowed to check out your project from the R Forge repository Browse to some folder where you d like to check out your project from the R Forge repository l d suggest making a new folder in which to keep ongoing snap shots of the repository because you may be periodically updating your project over the weeks and months to come Right click in the empty space of the folder to pop up the context menu see Fig ure 6 13 Since you have installed TortoiseS VN some extra items specific to Tortoise SVN appear in this context menu Select SVN Checkout from the context menu alternatively you could go to your 42 t PuITY Key Generator File Key Conversions Help Key Please generate some randomness by moving the mouse over the blank area Actions Generate a
24. How To Make an R Package Based on C And Manage It With R Forge A Tutorial Jos M Maisog Medical Numerics Inc and Georgetown University Medical Center joe maisog medicalnumerics com jmm970georgetown edu http howtomakeanrpackage pbworks com Version 1 14 January 11 2011 Table of Contents List of Figures 1 2 Introduction Software Setup 2 1 Software For Making R Packages Based on CLL oe ZLO R reguired iue x eae 212 RTIools required eee 2 13 MiKTeX optional 2 1 4 Microsoft HTML Help Workshop optional 215 perl optional avis ros o n 2 1 6 Set Up Your Windows Path Variable 2 1 7 Dev C or NotePad optional Software for Using R Forge Zl TortoiseSVN ee ceed as ae ba ee SEINE uus Sis oe EUR OG OS RR e Example C Code A Simple Matrix Class 3 1 3 2 3 3 BIEN ias Reseau SE aru 2004 4 424544 an440846 264445 teat R Maker 2o ha nen soy RAK A BRR SG Make a Shared Dynamically Linked Library 4 1 4 2 4 3 4 4 4 5 4 6 4 7 Kintertace ce 2 2222 a v r onn Run ROMD SHLIB 2 e x n Load the DLL into R Check that the DLL has been properly loaded MatrixMult T oo esans a aw k e eRe ee Test the R Wrapper Function Unload the DLL 42 42222225 Make An R Package 5 1 5 2 Create the R Package Folder Structure Run RCMD CHECK uui uem starei 5 3 The DESCRIPTION and NAMESPACE f
25. This step allocates memory that the C code will use nrowA nrow A ncolB ncol B multResult matrix rep 0 nrowA ncolB nrow nrowA Invoke C function CWrapper The first argument of C is the name of the C wrapper function The rest of the arguments provide pointers to six R variables in order 1 The matrix multResult which will contain the result of multiplication 26 2 The number of rows in the first matrix 3 The number of columns in the first matrix 4 The number of columns in the second matrix 5 The actual values of the first matrix 6 The actual values of the second matrix output C CWrapper product as double multResult dt dk dt nRows as integer nrow A nCols as integer ncolA nCols2 as integer ncol B matrixi as double A matrix2 as double B Reshape product back into an nrowA by ncolB matrix Then return the matrix multResult matrix output product nrow nrowA return multResult 4 6 Test the R Wrapper Function In an R session source the file MatrixMult r so that the R wrapper function MatrixMult is defined source C Your Folder MatrixMult r Then define two matrices A and B and multiply them in R A matrix 1 6 nrow 2 B t A Producti A B print Product1 The print function should produce the following output gt print Product1 1 2 1 35 44 2 44 56 Then use the Mat
26. at RMat DeallocateMemory Assignment operator 1 RMat amp RMat operator const RMat amp vRhs 1 DeallocateMemory AllocateMemory vRhs NumRows vRhs NumCols for int i 1 i lt mNumRows i for int j 1 j lt mNumCols j 1 this i j vRhs i j T J gt return this Assignment operator 2 RMat amp RMat operator double vValue for int i 0 i lt mNumRows mNumCols i mValues i vValue F return this Multiplication operator RMat RMat operator const RMat amp vRhs assert mNumCols vRhs mNumRows RMat vProduct mNumRows vRhs NumCols for int i 1 i lt mNumRows i for int j 1 j lt vRhs NumCols j 1 for int k 1 k lt mNumCols k 1 vProduct i j this i k vRhs k j 17 T F return vProduct Element access double amp RMat operator int x int y const t Basic range checks if x lt 1 l C x gt mNumRows Il Cy lt 1 Il Cy gt mNumCols t cerr lt lt Rmat operator range error lt lt endl return double amp mNaN T Offset is y 1 mNumRows x 1 rather than x 1 mNumCols y 1 because we want to organize memory the same way as it is in an R matrix R is column major Reference http en wikipedia org wiki Row major orderitColumn major order return mValues y 1 mNumRows x 1 Y Transpose
27. at4 result numRows numCols2 vMat4 0 0 Initialize to zero for int i 1 i lt numRows i for int j 1 j lt numCols2 j 1 for int k 1 k lt numCols k 1 vMat4 i j vMati i k vMat2 k j T 23 T F vMat4 RPrint CppMultiply way down in the C code nvMat4 n When program execution finishes the above three nested FOR loops vMat4 will contain the result of multiplying the two matrices When program execution exits this function vMat4 will go out of scope but the result of multiplication will remain in memory Note that the RMat destructor does NOT deallocate memory if it did result of multiplication would be lost when vMat4 goes out of scope Not to mention the problem of deallocating memory in vMati and vMat2 CWrapper C function that in turn invokes the above C function CppMultiply R can access C code but can t access C code directly This C function provides a C interface to the C code that R can access See http www parashift com ctt faq lite mixing c and cpp html In this C function you must NOT include class declarations instantiate any C objects or do any oher obvious C things The EXTERN statement tells the C compiler that the enclosed function CWrapper is a C function Although apparently we can insert C style comments and we can even declare variables in the middle of the funct
28. atively you can select Packages gt Install package s from local zip files from the R menu Load the multmat library into R with the usual command library multmat Check the documentation for the project by trying these four commands at the R prompt multmat MatrixMult TA TB The documentation is extremely minimal because we made the minimum number of changes necessary in the Rd files to get the R package to build When you get around to mak ing a real package you ll need to flesh out the documentation much better than we have here For details on the various sections in the Rd files see chapter 2 of 8 URL http cran r project org doc manuals R exts htm1 Writing R documentation files As mentioned earlier the documentation markup language is very similar to BTEX Try running the example from the documentation page for the multmat package by typing the following commands at the R prompt 33 data A data B C MatrixMult A B You should see the following output CppMultiply way down in the C code vMat3 35 44 44 56 CppMultiply way down in the C code vMat4 35 44 44 56 Also the matrix C should now be the product of matrices A and B gt 1 L 2 1 35 44 2 44 56 You can confirm that we got the right answer by using R itself to compute the matrix product gt A B 1 2 1 35 44 2 44 56 During the course of developing an R package you mig
29. ave built a example R package named multmat based on underlying C code Don t submit this example package to R Forge I don t think that the R Forge team wants you to submit test R packages that don t really do anything I think that if you submit a test R package to R Forge the project won t be approved and you won t get past section 6 2 Submit only real R packages to R Forge Note that there is a similar website named R Forge located at http www rforge net This tutorial doesn t use that website In retrospect I am wondering whether Tom Lumley had been referring to this RForge rather than the R Forge that I ultimately used The following sections step you through the basic use of R Forge 35 6 1 Create Your R Forge Account Go to R Forge http r forge r project org You should see the R Forge as shown in Figure 6 1 Create an R Forge account and then log in After you log in the web page should look something like Figure 6 2 6 2 Register Your Project After logging in to R Forge click on the link Register Project The resulting web page should look similar to Figure 6 3 Fill in the information to register your project Again don t submit the example multmat package to R Forge Submit only real R packages to R Forge After your project is successfully registered a link for the project will appear under the Projects tab see Figure 6 4 Clicking on that project link will bring you to a page for
30. ble mValues Matrix values int mNumRows mNumCols Matrix dimensions double mNaN Return NaN on bad input F3 endif _RMAT_H defined 3 2 RMat cc include RMat h For RMat class include limits For NaN include lt iostream gt For cout cerr endl and flush include lt assert h gt For assert if COMPILE_WITH_R include R h For Rprintf endif using std cout using std cerr using std endl using std flush Constructor 1 RMat RMat mValues 0 mNumRows 0 mNumCols 0 mNaN std numeric limits lt double gt quiet NaN T Constructor 2 RMat RMat int x int y mValues 0 mNumRows 0 mNumCols 0 mNaN std numeric limits lt double gt quiet NaN 1 AllocateMemory x y T Constructor 3 This constructor will be used to point an RMat object to the memory location provided by R via the C function RMat RMat double vElements int x int y mNaN std numeric limits lt double gt quiet NaN 1 mValues vElements mNumRows x mNumCols y 16 T Constructor 4 copy constructor RMat RMat const RMat amp vRhs mValues 0 mNumRows 0 mNumCols 0 mNaN std numeric limits lt double gt quiet NaN 1 AllocateMemory vRhs NumRows vRhs NumCols O for int i 1 i lt mNumRows i t for int j 1 j lt mNumCols j this i j vRhs i j J Destructor RM
31. d ls commands under UNIX 3 At the DOS prompt invoke the dir command You should see the multmat folder listed 4 At the DOS prompt type the following command rcmd check multmat The last step will perform a check on the multmat folder to see whether it is ready to be built into an R package At this point of the tutorial the multmat folder is not ready to be built into an R package so you should see an error message like informing you that it cannot be installed The very last line should indicate the folder path to a plain text log file with a name like OOinstall out that contains details regarding the check failure Open this file in a plain text file and examine the contents it should contain an error message indicating that no packages were specified We will remedy this shortly in section 5 5 5 3 The DESCRIPTION and NAMESPACE files Examine the contents of the DESCRIPTION file using a plain text editor You ll note that it contains basic information on the package such as the name a very short title and 30 the author Leave this file unchanged for now Although we won t get into it here note that the DESCRIPTION file has a line for the type of license that you want to make your package available under See http www r project org Licenses and Section 1 1 1 in 8 for more information about licenses Create a plain text file named NAMESPACE in the multmat folder i e in the same folder as the DESCRIPTION file Mak
32. de folder by clicking on the little square button with an icon of a folder tree structure browsing to the R include folder then clicking on the Add button you must click on the Add button This is illustrated in Figure B 4 You can now dismiss the Project Options dialog box Then select Execute Compile This should build the stand alone executable Then select Execute Run This should run the program You should see the same output that you saw in chapter 3 But in addition you should see this line at the end Using R math library to compute R_pow 2 3 8 This demonstrates that the C code successfully accessed the R math function R pow 59 Project Options Files Compiler Parameters Directories Build Opti Makefile Version info Figure B 1 The Dev C Project Options dialog box 60 Project Options General Files Compiler Parameters Directories Build Opti Makefile Version info Additional Command line options Compiler C compiler X conca ek Figure B 2 The Dev C Parameters dialog box 61 Project Options Ek Replace Add Delete Delete Invalid Pte Figure B 3 The Dev C4 4 Library Directories dialog box 62 Project Options General Files Compiler Parameters Directories BIEN NE Makefile Version info ua Include Directories B she Olt ica C Program FilessRsR 2 10 1 include Ek Replace Add Delete Delete Invalid
33. double vValue RMat operator const RMat amp vRhs Constructor 1 Constructor 2 for x by y matrix Constructor 3 for R interface Constructor 4 copy constructor Destructor Assignment 1 Assignment 2 Multiplication double amp operator int x int y const Element access Some utility functions RMat Transpose int NumRows const int NumCols const void Print void Print const char vString if COMPILE_WITH_R Transpose Returns number of rows Returns number of columns Print matrix to stdout Print matrix to stdout with string 15 void RPrint Print matrix to R console void RPrint const char vString Print matrix to R console with string endif A function for deallocating memory is made publicly available because I want to not only run test this code in a pure C test program outside of R testRMat cc but I also want to run this code from within R In the latter case will let R handle memory management This means that I can t automatically deallocate memory in the destructor which is the usual thing one might do For symmetry the function for memory allocation is also made publicly available although it didn t have to be Maybe it should be private bool AllocateMemory int x int y Allocate memory for x by y matrix void DeallocateMemory Deallocate memory private dou
34. e the contents of the NAMESPACE file the following two lines useDynLib multmat export MatrixMult This tells R that we need to load a shared library named multmat dll as well as the R function MatrixMult defined in the file MatrixMult r 5 4 Add src folder for C Code Create a subfolder named src in the multmat folder The multmat folder should now have four subfolders man data R and src In the new src subfolder place the files RMat h RMat cc and RInterface cc Be sure that you have edited the file RMat h so that the line define COMPILE_WITH_R O now reads define COMPILE_WITH_R 1 as described in section 4 2 You don t need to include the file test RMat ce since this was only a stand alone program that tested the C class RMat But I have found that it seems to be okay if you do include this file 5 5 Fix the Documentation Files Examine the file O0install out created by the remd check command in section 5 2 You will see an error message stating Warning man multmat package Rd 34 All text must be in a section Warning man multmat package Rd 35 All text must be in a section This indicates that the section definition in the file multmat package Rd is empty and that you should look at lines 34 and 35 Edit the file multmat package Rd with a text editor you ll note that the formatting in this file is similar to IXTEX Note that lines 34 and 35 are Dptionally other standard keywords one per li
35. em C Program Files MATLAB R2007a Student bin C Program Files MATLAB R2007a Student bin win32 C DATA Program Files Perl bin C Program Files TortoiseSVN bin C Program Files SAS SharedFiles Formats C Program Files Executive Software DiskeeperLite C Program Files QuickTime QTSystem For Help press F1 Figure 2 4 Example of editing the Path variable in WordPad on the Start button in the lower left corner of your Windows desktop and select Run this should bring up the Run dialog box as show in Figure 2 5 Type cmd in the entry box and then click on the OK button This should then pop up a window containing an old fashioned DOS prompt see Figure 2 6 Alternatively you can select Start gt Programs Accessories gt Command Prompt Then type the following seven commands at the DOS prompt The first command path simply lists prints out the value of your Path variable The remaining six commands invoke various programs that are needed to create an R package path rcmd help gcc help perl help tex help grep help hhc help The latter six commands are listed in Table 2 1 If you run any of these commands and get an error message like command not found it means either that you haven t set up the Windows Path variable properly or that you haven t installed the software itself properly 10 Type the name of a program folder document or Internet resource and Windows will open it for you
36. exercises the member functions of the RMat class to demonstrate that it works Cut and paste the source code given in section 3 1 into a plain text file named RMat h Similarly place the source code given in section 3 2 into a file named RMat cc and the source code given in section 3 3 into a file named testRMat cc For your convenience a ZIP file file containing this source code is downloadable from this URL http howtomakeanrpackage pbworks com f Code zip At a DOS prompt see subsection 2 1 6 navigate to the folder containing the three source code files use the DOS commands chdir and dir to change and list folders in exactly the same way you d use the cd and ls commands under UNIX Then use gcc from MinGW to compile the test program gcc o testRMat testRMat cpp RMat cpp lstdc Then invoke the test program testRMat 14 If all went well you should see this output vMati LEE 2 4 6 vMat1 2 2 4 vMat2 3 5 7 4 6 8 vMat3 T 23375 2 4 6 vMat4 1 3 5 2 4 6 vMat5 1 2 3 4 5 6 vMat6 35 44 44 56 Now vMat6 0 0 0 0 Press any key to continue 3 1 RMat h ifndef _RMAT_H define _RMAT_H define COMPILE_WITH_R O class RMat public Constructors and destructor RMat RMat int x int y RMat double vElements int x int y RMat const RMat amp vRhs RMat O Overloaded operators RMat amp operator const RMat amp vRhs RMat amp operator
37. ht find it necessary to uninstall an old version of the package with a new improved version To uninstall the multmat R package run this command at the R prompt remove packages multmat Unfortunately I have found it necessary to completely exit R before attempting to re install a library Perhaps this isn t necessary but I haven t figured out a way around it If you know how to do this please let me know 34 Chapter 6 R Forge Cross Platform Builds and Submitting to CRAN R Forge http r forge project org 9 and 1 provides three pieces of functionality which we ll use in this tutorial e R Forge provides a central version controlled repository for R packages section 6 4 section 6 5 and section 6 6 This can be important for large scale projects which involve more than one developer Also if you discover that you have inadvertently introduced a bug while you re developing a package you can revert your package to a previous version e R Forge performs nightly builds for R packages on three platforms Linux Windows and MacOS see section 6 6 This is convenient because you might not have access to all three types of machines in my case I didn t have access to a Macintosh computer and so I relied on R Forge to build the MacOS version of the ptinpoly package e Finally R Forge provides a facility for you to submit your package from directly R Forge to CRAN section 6 7 At this point in the tutorial we h
38. iles sees 5 4 Add sre folder for C Code rv rv a 5 5 Fix the Documentation Files _ S0 Rm RCMD BUILD Laval seks de r e SEG sua KE Bee YU KER Ka 5 7 Install Uninstal Your R Package 2 2 224 4 var ee eee ee RA 6 R Forge Cross Platform Builds and Submitting to CRAN 6 1 Create Your R Forge Account epee eave E RS Do Register rour Peek ee ek CK ON SE upas wa sor qoem E YS es Do Conigure Your Sens a nudo kG wis oe dex EGEE QW OR BEES OA Cheek Oui Piles front R Forge o ote ps eats s kaka bee hee m w es 6 6 Modify Check Out Folder Contents 2 4 2 264 ee ot DD Commit Modiieation Io H Porge 1 2o oos kx EY eo x By muB Package to CRAN u l sasa kaa AG R4 9X9 X EERE FE OR N Bibliography A MinGW gcc Link Stand Alone Example C Code To R Libraries B Dev C Link Stand Alone Example C Code To R Libraries List of Figures 2 1 2 2 2 3 2 4 2 5 2 0 6 1 6 2 6 3 6 4 6 5 6 6 6 7 6 8 6 9 6 10 6 11 612 6 13 6 14 6 15 6 16 6 17 B 1 B 2 B 3 B 4 System FP PR 8 Environment Variables e 5842 ed rava ve b s kake se 9 Edit System Variables res ko casa s sasa RS s suq ee OS 9 Edit Fath m Wore ad ce edo s vo ks Ae et dr ey x RE do ewe RA 10 The Ron Daor DU ecne doeet use Stu eR E exe cS IE nw US 11 D BIO Q core que Q map pa Dae h quc E d Red Eee 4 e dg 11 R Forge Home Page o oc ee oe sss cuase se woa uq esa a X Y Ex ES 37 R Forge J
39. install Dev C then you ll have two copies of the MinGW Gnu compiler one from R Tools and one from Dev C It may be possible to set up Dev C so that it uses the copy of the MinGW Gnu compiler that came with RTools but I haven t looked into that Maybe somebody out there can confirm or refute this idea You can find a tutorial that I wrote on getting started with Dev C at this URL http scs gmu edu wss wss0804 shtml student 2 2 Software for Using R Forge If you d like to use R Forge to store and maintain your R project see chapter 6 you ll need to install TortoiseSVN and the PuTTY distribution 2 2 1 TortoiseSVN Subversion is an open source software for version control TortoiseSVN provides a nice graphical user interface GUI to Subversion functionality Download the TortoiseSVN distribution from this URL http tortoisesvn tigris org As an aside I thought at first that one needed to install both Subversion and Tortoise SVN and that TortoiseSVN would run on top of Subversion i e one would have both a Subversion process and a TortoiseSVN process running simultaneously on the computer I mistakenly thought it would be exactly analogous to the relationship between MiKTeX which provides IATEX functionality and TeXnicCenter which runs on top of Mik TeX and provides a nice GUI But it turns out that TortoiseSVN itself provides Subversion functionality so you don t need to install Subversion as well
40. ion which I thought you can t do in regular C result is a raw pointer to the result of matrix multiplication numRows and numCols is the number of rows and columns of the first matrix numCols2 is the number of columns of the second matrix The number of rows of the second matrix must be the number of columns of the first matrix this will be checked at the level of the R code mati and mat2 are raw pointers to the matrix elements of the two matrices extern C void CWrapper double result int numRows int numCols int numCols2 double mati double mat2 t Invoke second function which internally can do C things CppMultiply result numRows numCols numCols2 mat1 mat2 F 4 2 Run RCMD SHLIB Edit the file RMat h and change the line define COMPILE WITH R O to define COMPILE WITH R 1 This enables some lines of code that use R functions such as R print 24 Examine the newly enabled lines in RMat cc There you ll see the following function void RMat RPrint 1 for int i 1 i mNumRows i 1 for int j 1 j lt mNumCols j 1 Rprintf g this i j Rprintf n R_FlushConsole R ProcessEventsQ The RMat member function RPrint calls the R function Rprint which prints charac ter strings to the R console But the invocation of Rprint must be followed by calls to the two functions R FlushConsole and R_ProcessEven
41. ion Exam ine the file OOinstall out just to see what it looks like when remd check goes to completion without error Admittedly a few warnings are generated and ideally you d modify the pack age so that no warnings were generated But for the purposes of this tutorial we ll ignore the warnings and proceed A ZIP file containing a copy of the multmat folder that passes the remd check command can be downloaded from this URL http howtomakeanrpackage pbwiki com f multmat zip 32 5 6 Run RCMD BUILD To build a gzipped tarfile package for Linux rcmd build multmat This should generate a file named multmat tar gz You can use this file to install the multmat R package on a Linux machine To build a ZIP file package for Windows run this command instead rcmd build binary multmat This should generate a file named multmat zip You can use this file to install the mult mat R package on a Windows machine The ZIP files that these commands generated can be downloaded from the following URLs http howtomakeanrpackage pbwiki com f multmat_1 0 zip http howtomakeanrpackage pbwiki com f multmat_1 0 tar gz 5 7 Install Uninstall Your R Package To install the multmat package run this command at an R prompt install packages repos NULL pkgs C My Documents MultMat zip Of course you ll need to modify the value of the pkgs argument to point to wherever the ZIP file for the multmat package is kept Altern
42. l effects processor scheduling memory usage and virtual memory Settings User Profiles Desktop settings related to your logon Startup and Recovery System startup system failure and debugging information Settings Environment Variables Error Reporting Cancel Figure 2 1 The System Properties dialog box 6 Copy and paste the contents into a text editor like WordPad or NotePad see subsection 2 1 7 below T In the text editor add the following folders to the beginning of the list of folders so that they are searched first Delimit folders with semicolons as per the Path variable convention see Figure 2 4 e R bin this is the folder in which your R executable R exe is kept On my system this is the folder C Program Files R R 2 10 1 bin of course the exact path name may differ on your own system e RTools bin this is a subfolder of your RTools installation On my system this is the folder C Rtools bin e MinGW bin this is another bin subfolder of your RTools distribution On my system this is the folder C Rtools MinGW bin e perl bin Recent versions of RTools come with perl kept in a separate bin folder in the R Tools distribution e g C Rtools per bin e MiK TeX If you have indeed installed it E g C Program Files Mik TeX 2 7 miktex bin e HTML Help Workshop If you have indeed installed it E g C Program Files HTML Help Workshop Again as per Alan Lenarcic
43. ly builds are completed you can check the build logs for problems by going to the Contributed R Packages page for your R project In Figure 6 17 note the table with four columns two for Linux 32 and 64 bit and one each for Windows and MacOS If you want to see whether there was a problem with e g the Windows build click on one of the patched or devel links in the Windows column 48 View b Arrange Icons By gt Refresh Customize This Folder Undo Rename Ctrl Z ies Checkout WP TortoiseSVN gt New b Properties Figure 6 13 TortoiseSVN Context Menu To install the package directly from R Forge type e g within the R environment install packages your R package repos http R Forge R project org P E y P g P P g proj g 6 7 Submit R Package to CRAN Submitting your R package to CRAN from R Forge is trivial Just go to the Contributed R Packages page and click on the link Submit this package to CRAN found just below the table for the Linux Windows and MacOS builds see Figure 6 17 Now you must wait again It may take a few days for your R package to show up on CRAN Also don t be surprised if one build shows up quickly on CRAN whereas another build takes a few more days to show up the different builds are apparently managed by different teams and at any one time one team may be busier than another I don t think that the builds are automated to the extent that they are on R Forge
44. ne from file KEYWORDS in 77 the R documentation directory 3l Remove these lines or insert percent signs at the beginning of each line to comment them out and re run the remd check multmat command It will still generate an error message Examine the file O0install out again This time you will see an error message stating Error in Rd info db i l Rd files must have a non empty title This indicates that at least one of the Rd documentation files has an empty title section Edit the file MatrixMult Rd You ll see that line 5 contains this text function to do Recall that in IATEX a line beginning with a percent sign is a comment So the title section lines 4 6 in the file MatrixMult Rd is considered empty Change the title section in the MatrixMult Rd so that it now look like this title Example function to multiply matrices The title section in the files A Rd and B Rd are also empty Edit both of these files so that their title sections look like this title Sample data matrix Re run the remd check multmat command This time you ll see this error message Error unexpected symbol in simple examples 5o there s a problem in the examples section of one of the Rd files Edit the file multmat package Rd so that the examples section looks like this examples data A data B C MatrixMult A B Re run the remd check multmat command This time it should go to complet
45. noid seDexoed jje jo 1si e SI wojeg sebeyred y peinqriquo urwpy eBeg yuawidojanag Y sabeyoed N wos sisi unupv fueuiuns uopeu jod ui jueuiurejuoo JUIOA 1011591 921 12efo1d abed AW ws oL dwnr INO youeas paoueapy ees palod amus y uo sss r OJ v speunjooq 240 T e am kara LF vem T svam i usw D es m m wavs Pi Ig 16 Ieue oH A yeu szuosno 7 Y Z 65 pi dno1B 4 B10 paloud r 3610j 4 sdu g 3 gt x uoojulod 104 1531 361044 e Figure 6 17 R Packages Page Note table with four columns two for Linux 32 and 64 bit and one each for Windows and MacOS Also note the Submit th link just under the table kage to CRAN is pac 54 Bibliography R Forge Administration and Development Team R Forge User s Manual BETA Tech nical report The R Project 2009 J Chambers Software for Data Analysis Programming with R Springer New York 1st edition 2008 RJ Hyndman Building R packages for Windows Technical report Monash University 2008 F Leisch Creating R Packages A Tutorial Technical report Ludwig Maximilians Universitat M nchen and R Development Core Team 2009 A Lenarcic R Package Writing Tutorial Technical report Harvard University 2008 J Liu YQ Chen JM Maisog and G Luta A new point containment test algorithm based on preprocessing and determining triangles Computer Aided Design 42 12 1143 50 2010 JL Schafer How to Make
46. of C objects However it does make a call to a function CppMultiply that itself instan tiates and uses C RMat objects The C code is thus hidden from R by the intervening C wrapper function CWrapper e The C wrapper function CWrapper is enclosed in an extern statement indicating that it is a C rather than C function For some reason you need to hide C code from R presenting R with only a C interface my guess is that the part of R that interfaces with C C code was compiled in C not C Within the C code however you can then make calls to functions which themselves use C The C code thus functions as a sort of wrapper for the C code 22 include RMat h include R h R functions include Rmath h Rmath The first one is a C function named CppMultiply that directly accesses the C RMat class The second one is a C function named CWrapper that INdirectly accesses the C RMat class via a call to CppMultiply CppMultiply C function which uses the RMat class defined in RMat h and RMat cpp Since it is a C function it cannot be called directly from R but instead will be called through an intermediary C function CppMultiply defined below result is a raw pointer to the result of matrix multiplication numRows and numCols is the number of rows and columns of the first matrix numCols2 is the number of c
47. olumns of the second matrix The number of rows of the second matrix must be the number of columns of the first matrix this will be checked at the level of the R code mati and mat2 are raw pointers to the matrix elements of the two matrices void CppMultiply double result int numRows int numCols int numCols2 double mati double mat2 RMat vMat1 mati numRows numCols RMat vMat2 mat2 numCols numCols2 Compute matrix product using overloaded operator just to demonstrate that we get the same answer RMat vMat3 vMati vMat2 vMat3 RPrint CppMultiply way down in the C code nvMat3 n Use Constructor 3 to point vMat4 s mValues pointer to the memory location provided by R Note that this constructor assumes that memory allocation deallocation will be managed up in the R level not down here in the C code Then manually compute the matrix product We couldn t use the overloaded multiplication operator as we did with vMat3 above because the first thing that the overloaded assignment operator does is deallocate memory This means that the memory location that R provided would probably become corrupted or inaccessible In any case you re not supposed to use the regular C delete statement with memory that was allocated by R This is still using C stuff we re using the overloaded operator RMat vM
48. on MatrixMult as described previously in section 4 6 Then run the following R commands rObjects cC A B MatrixMult package skeleton name multmat path C Your Example Folder list rObjects This should create a folder named multmat which in turn contains three subfolders named R data and man as well as two plain text files named DESCRIPTION and Read and delete me This new multmat folder will be placed in the folder specified by the path argument in the call to package skeleton you should modify this to point to some appropriate folder on your own system The subfolder R should contain an R script named MatrixMult r which contains the def inition of the function MatrixMult The subfolder data should contain two R data files A rda and B rda which contain the two example matrices Finally the subfolder man should contain four R documentation files multmat package Rd multmat package Rd A Rd and B Rd these files will be further discussed below in section 5 5 You can open these files in a plain text editor such as WordPad or NotePad if you do so you will see that the content of these files looks very similar to IXTEX The path of the package skeleton command indicates where you d like to create the R package folder skeleton At the end of his tutorial A Lenarcic notes that your choice of where to place this folder can cause problems I have noticed this myself intermittently 29 and am not sure
49. outside or exactly on the polyhedron Dr Luta thought that a possible thesis project for me might be to wrap up Dr Liu s C code into an R package and then write a thesis examining the use of the code on some real data the idea would be to perform gating on three variable flow cytometry data See e g Matt Wand s curvHDR package As it turned out I did my thesis topic on a completely different different topic non negative matrix factorization Still with some encouragement from Dr Luta I continued work on building an R package from Dr Liu s C code It took a while for us to figure out how to do this Chapter 4 from Chambers book 2 was helpful as was Rob Hyndman s tutorial 3 But the single most important document for my purposes was Alan Lenarcic s tutorial 5 although it doesn t quite get through the entire process this document got me about 95 of the way there It took me a while to figure out the remaining 596 but with lots of help from my classmate Yuan Wang I finally created the C based R package ptinpoly There was still one problem on my Windows system I was able to make builds only for Windows and Linux but we also wanted a MacOS build And it seemed that I needed access to a Macintosh computer in order to create a build for MacOS but nobody I knew had a Macintosh computer that I could use So for a while only Linux and Windows builds of the ptinpoly package were available In retrospect I now think that I
50. r from within a script This like the Path environment variable under Lin ux UNIX or to the MATLABPATH variable for MATLAB If the program isn t found in any of those folders and if it isn t a native DOS command such as CHDIR MKDIR RMDIR and so on then an error is generated even though it may be a program that you have in fact installed somewhere you still need to tell DOS where it is You need to set up the Path variable so that it contains the folders listed in Table 2 1 5 These are the executables that you have installed in the previous subsections The steps to modify the Path variable are listed below this is a somewhat meticulous and tedious step A Lenarcic called it awkward so be careful If you get any of the folder paths wrong the rest of this tutorial will probably not work 1 On your computer desktop double click on the icon labeled My Computer This should pop up a window as shown in Figure 2 1 2 Select the tab labeled Advanced 3 Click on the button labeled Environment Variables This should pop up a window as shown in Figure 2 2 4 Select System Variables This should pop up a window as shown in Figure 2 3 5 Click in the entry box labeled Variable value and select the entire contents 7 System Properties System Restore P Automatic Updates Remote General Computer Name Hardware Advanced i You must be logged on as an Administrator to make most of these changes Performance Visua
51. rixMult function to perform the matrix multiplication Product2 MatrixMult A B print Product2 You should see the following in the R console gt Product2 MatrixMult A B CppMultiply way down in the C code vMat3 35 44 44 56 CppMultiply way down in the C code vMat4 35 44 44 56 gt print Product2 1 2 1 35 44 2 44 56 gt This confirms that the R function MatrixMult which invokes the C wrapper function CWrapper which in turn invokes the C function CppMultiply which computes the matrix product gets the same answer that R does 27 4 7 Unload the DLL When debugging your C code and testing it in R you may need to fix your C code and then re build the DLL But you won t be able to re build the DLL if you currently have it loaded in an R session You must first unload the DLL from R before attempting to rebuild it To unload the DLL run the dyn unload command at the R prompt dyn unload C YourFolder multmat d11 Now that you have unloaded the DLL you can proceed to re build it using remd SHLIB as in section 4 2 and then re load it into R as in section 4 3 28 Chapter 5 Make An R Package Once you ve got the DLL and R wrapper function working properly chapter 4 you can then proceed to make an R package 5 1 Create the R Package Folder Structure Get into an R session if you aren t already in one In this R session define matrices A and B as well as the R functi
52. tice any errors in this tutorial please let me know Chapter 2 Software Setup In this chapter I discuss the software needed for this tutorial It is assumed that you have root privileges on your computer so that you can install the software If not you ll need the system administrator to install the software for you if you don t already have the necessary software installed In the first section I go over software for making R packages based on underlying C code while in the second section I cover the two pieces of software you ll need to use R Forge 2 1 Software For Making R Packages Based on C 2 1 1 R required This may be obvious but you ll need a copy of R URL http www r project org itself to be installed In the bin subfolder of the R installation there is in addition to R exe itself a utility program named Remd exe which we ll use to check section 5 2 and section 5 5 and build section 5 6 R packages 2 1 2 RTools required RTools URL http www murdoch sutherland com Rtools is a suite of utilities for R It provides a version of the Gnu C C gcc compiler called MinGW which we ll use in the next chapter Recent versions of RTools also include perl which I believe is required for running the rcmd utility program that comes packaged with R itself At least if I try to run remd on a machine that has R installed but not RTools or perl I get an error message about perl not being found 2 1 3 MiK
53. to build an R package based on FORTRAN 95 and a tutorial by Leisch 4 in which he describes how to build an R package based solely on R scripts i e not based on compiled languages like FORTRAN or C This document is my attempt to put together in one place the things I ve learned about building a C C based R package and then managing it using R Forge In the first chapter of the tutorial I step you through the installation of required software Then in the second chapter I introduce you to a small C class that we ll use for the tutorial in that chapter we ll build a small test program that exercises the class without involving R In the third chapter I first step you through the process of building a dynamically linked library DLL from the C code and then accessing that DLL from within R then I step you through the process of building an R package based on the C code In the final chapter I show how to use R Forge to make Linux Windows and MacOS builds of your R package and how to transmit your R package from R Forge to CRAN Now this tutorial may already have been rendered obsolete by the recent development of an interesting R package Repp URL http dirk eddelbuettel com code rcpp html but for what it s worth here s my take on the matter l m running a Windows XP system so this tutorial is Windows centric Still I think that many of the procedures should be very similar under either Linux or MacOS If you no
54. ts otherwise the character out put won t be printed immediately Apparently character strings get stored in some buffer that needs to be manually flushed For more on the R API see Chapter 6 of 8 URL http cran r project org doc manuals R exts html The R API That chapter lists many of the R functions that you might like to try calling from C C code Then to create a dynamically linked library run the following command rcmd SHLIB RMat cc RInterface cc o multmat dll This should create a new DLL file named multmat dll 4 3 Load the DLL into R To load the multmat DLL into R run the following command at the R prompt dyn load C YourFolder multmat dll As usual you ll need to change the exact path to the multmat dll file to reflect the actual folder structure on your own system 4 4 Check that the DLL has been properly loaded To confirm that the DLL has been properly loaded run the following command at the R prompt is loaded CWrapper It should return TRUE rather than FALSE 25 4 5 MatrixMult r The R function MatrixMult defined below doesn t do much beyond calling the C wrapper function CWrapper which in turn calls the underlying C code Cut and paste this code into a plain text file named MatrixMult r For your convenience the code is down loadable from this URL http howtomakeanrpackage pbworks com f MatrixMult r There are two things to note about MatrixMult 1 First note that this R f
55. u might want to update the date and version number in the DESCRIPTION file When you re all finished commit your modifications to R Forge as described in section 6 6 Don t forget to re submit the package to CRAN 53 TNE l NV Woy 6 Ajodund 339 eseejey ejqeis 9 AY LO P6 9P 8L LEOL OLOZ eDueuo jse7 6 uoisiSA 510 309toad u 9b510g u d33u sodea ATodut3d sebexoed rre3sur d 1 y utum Apnoeup abeyoed siu jesul oL E NYY 01 eBexed siu puqns v N je ep peuo1ed Sulo je ep peuojed Uyo 2euo jeg Y N lanap payoyed Je ap payazed paysyed payjed ping Ajeq puedoa X SOWN v9 98x ZE 98X SMOPUM y9 9gxxnur ZE 98X xnu sb01 z6y Meud piedo l x soen drz Meud u31e ninui smopursg ZB 1611 8234n0s abeyoeg peojumog us uu Je nbueu e Aq pauyep ea2eyns peso 2ue ue episino Jo uo DEXE uiyym SI adeds qg ul jurod e jeujeuw sse U3IUA pedid uonounj e sepiioud fueiqi stu p Ge 1581 uojpau lod ur 1utoq Ajodund e npeuos siu 01 Buipio22e pex2euojinq ase sabeyoed Iy 40 suoisia Japjo ul zB je1 sa2unos abeyded ay woy jesui jaaewaye JO Y JO UOISJAA JUBDAI JSOW ay 01 YINMS 0 aney noA abso4 y uo papnosd sabeyoed BY IIg1sui l njss 33ns 01 JAPJO U SUOISJAA Jepjo 104 JOU ING 4 JO UOISJAA JUSS JSOW ay 104 AjUO seueuig s u1 s pnosd 36104 4 seueutq abeyIed 10 ajou jueyiodui uoupeu Jod ur 3ueuiurejuoo jurod 104 1591 17916170 Aq papi
56. unction makes a call to the R function C which accepts the name of the C wrapper function CWrapper as one of its input arguments It will be able to access the C wrapper function if the DLL has been properly loaded which we checked in the previous subsection 2 Also note that this R function makes some basic checks on its input arguments such as making sure that the input is numeric and of the proper dimensions Sometimes such checks can be placed down at the level of the C wrapper function or perhaps even at the C level Schafer offers some suggestions for where to place checks 7 This R function might itself be considered a wrapper function Therefore it had been tempting to name it RWrapper but I thought that it would be better to give it a more descriptive name MatrixMult since this is the function that the user will interact with in practice MatrixMult function A B Make sure A and B are numeric if C C is numeric A is numeric B print MatrixMult input must be numeric return NaN T Make sure A and B are matrices if C is matrix A is matrix B print MatrixMult input must be matrices return NaN T Check inner dimensions of matrices ncolA ncol A nrowB nrow B if ncolA nrowB print MatrixMult improperly dimensioned matrices return NaN Create a matrix of zeros which will hold the result of multiplication
57. uss pue 8j020101d qnd A1quepr uss ye paved aq jm Aay qnd eu Z 10 030 01d yjog asn ue nOA u B5 y uss uieibo1d y uni Aay d1gnd e ayesauab o e ap JNOY euo e 104 moyje aseajq Ajejeipeuirui uaddey jou Aew y os qof uos e Aq euop si siy ay s ex pezuoune uss 1no ul sawas SAD y uo p 2eld eq JIA u1 pue aiay s ex qnd unoA peojdn Aew no juno22e Jadojanap HSS SA2 1no 10 euin Hana plomssed snoA ed o Burney piore og pofoig 18151683 e2ueuejuregy 3uno22y s oN 2 Merg eBeg jeuosiag Ay 11 Pod abed AN 9uioH o dwn pino 5 J _ IX 9DJO D stampa apo D lt Dum D unsa 7 vpn U svenn wiswo D abs i qvi su F evs rewsies geuekonqA ewa LA szumsno 7 o dyd sAayyssupa 1uno gt de B10 paloid 1 3610j 4 SANY 8 2 E Figure 6 10 R Forge Edit Keys Interface Paste your public key into the entry field 46 29 7C wes Figure 6 11 Pageant System Tray Icon It looks like a computer monitor wearing a hat 6 5 Modify Check Out Folder Contents The check out folder may contain several folders with names like pkg and web If you see this set of folders place the contents of your R package into the pkg folder i e place your data man R src folders and DESCRIPTION and NAMESPACE files into the pkg folder If the check out folder is empty then place the contents of your R package directly into it 6 6 Commit Modification To R Forge
58. ust After Logging In Rem GSO 38 R Forge Register Project Page eee eee ee 39 H Porge My Projects c a sss a s sns s s e ka KE 40 R Forge Project Page su peek s s e weas t w mo s k be EP s RR RE BEES Es 41 PuTTY Key Generator Start Up o on RR Roe 42 PuTTY Key Generator generating keys vnr aka 43 PuTTY Key Generator keys generated llle 44 R Forge Account Maintenance Page 22e 45 R Forge Edit Keys Interface RR Rs 46 Pageant System Tray Item soso cao oz o Le Ka LEG rigar 47 Pageant Add Key Dialog De u ee asss REE MOREE Oe 3 48 TortoiseSVN Context Men eco e 2644448444864 a s eu RR 49 TortoiseSVN Checkout Dialog Be vage AER xw 50 TortoiseSVN Context Menu With Commit Option 51 Tortoises VN Commit Dialog BOX oo ac s ox E Oe wee ee Rex wn 52 EEE s Ag Ra S 43 4 ERAN w ESSE P RA 54 Dev C Project Options e e R 60 Dev C Parameters aoaaa 61 Dev C Library Directories 00202 eee ee ee 62 Dev C Include Directories llle 63 Chapter 1 Introduction On January 13 2009 my thesis advisor George Luta forwarded me some C code pro vided by Jianfei Liu a computer scientist engineer based in Peking University Dr Liu s code performs a point containment test given a closed three dimensional polyhedron defined by a triangular mesh and given a point in three dimensional space the code tests whether the point is inside
59. yediomed 01 noA moje jim siu uibo uay pue sasn ays e se 18jsiBa1 0 paeu No 36104 4 jo 1no 1souu ay JAG 0 apio U iunuuuuo2 Y 204M eu 104 uiopeld V uonensiuiupe paseq qe e101 pue sdnyoeq inj PEAYDJE ajy 3ueueuued Bunsoy ays suniojspieoq abessaw Burgoen Bnq sisi Buijiguu seBexoed pex2euo pue ying jiep NAS ur 1590 u 01 sse22e see Buu jo ab10 4uoisn4 uo peseq s 3 syosloid Jayunj pue asemyos payejai y seDexoed y jo juawidojanap y Jo uuogejd eue e siayo aBs04 y son jeuvape 8 86 aBeyoe gy A60j033 yunwwop uebarf 0 00L uoneuuojut Jayyny 104 eBedeuiou joefosd 4 ay 1nsuo2 aseajq 31e Buuejsn uoneoyisse o sisAjeue seues aui s1s 1 99M Stu SANIV ISON jeonsnejs Buijjepoui jeeurjuou pue JEaUI s nbiuu3 1 ed1yde1b pue eonsnejs jo Moug epi e sapiaoid E YRZ si sn palaysibay yoiym soiydes6 pue Bunnduuo3 jeansijeis 10j jueuiuoJi ue pue eBenBue ejqejree Ajaay e S NNI S H 798 s1p loiq paysoy sonsners a6104 4 361044 pue y aie JEYM 3811 12efoud ebed A WOH junoooy man ui 507 ss X dnoip areyos 26104 v 7 speunjoog PO C lt Dum S yea 7 wom U sven 16 wswo as aw amp yew E oss ews i gueliou pA jew pA 3240sm TJ ve B10 palosd r3b10j1 O O gt awonjan 3640 u Figure 6 1 R Forge home page 37 Ansen NISNOOSIM VNN3IA eB104 9 uon NA 0 SYUEYL no 0 paubisse sway 134921 uado ou

Download Pdf Manuals

image

Related Search

Related Contents

User Manual - LuckinsLive.com      User`s manual - Carl Wittkopp Tresortechnik  MA2012-4  OM, KLIPPO, Energy, 2008-05  

Copyright © All rights reserved.
Failed to retrieve file