4

I am trying to try some C code from base R. I may need to modify the code and compile it to understand how it works.

For example, I am trying to understand the function C_modelmatrix.

One thing can be done is that I directly modify the source code src/library/stats/src/model.c where modelmatrix() is defined. But I will need to compile the whole R source and load this newly modified R, each time when I modify C_modelmatrix. This process is not efficient.

Another way is to only extract the related C code and compile it as an .so file. Then load the .so file with an existing R. But this approach seems to be difficult. I'm yet to figure out an exact procedure on how to do this.

Does anybody have any suggestions on what might be the best way to play with the C code in base R?

user1424739
  • 11,937
  • 17
  • 63
  • 152
  • They use makefiles, have you tried editing and recompiling? – ryanpattison May 19 '15 at 20:18
  • 2
    If you are intending merely to explore and do not need to *replace* the base function in all of *R*, then I recommend starting with Rcpp ([cran](http://cran.r-project.org/web/packages/Rcpp/index.html), [homepage](http://www.rcpp.org)). If you are looking to use your modified function (be it `model.matrix` or another), then I know of no way other than recompiling all of *R* (grunt). – r2evans May 19 '15 at 21:12

1 Answers1

4

I have my source directory (from svn) in ~/src/R-devel

~/src$ svn co https://svn.r-project.org/R/trunk R-devel
... (additional commands, e.g., R-devel/tools/rsync-recommended

I build in ~/bin/R-devel/

~/bin/R-devel$ CFLAGS="-g -O0" CXXFLAGS="-g -O0" ~/src/R-devel/configure
~/bin/R-devel$ make -j

I would make a change in ~/src/R-devel/src/library/stats/src/, then inside the directory ~/bin/R-devel/src/library/stats I can run

~/bin/R-devel/src/library/stats$ make

and only the stats package will be compiled / installed.

For exploring C code I actually prefer to use gdb to step through and interact with the code, with some hints available.

Martin Morgan
  • 45,935
  • 7
  • 84
  • 112
  • I see the following error when I try `R -d gdb`. Do you know what is wrong? `(gdb) run Starting program: /Users/username/doc/src/R/r-devel/R-3.2.0/bin/exec/R Unable to find Mach task port for process-id 14978: (os/kern) failure (0x5). (please check gdb is codesigned - see taskgated(8))` – user1424739 May 20 '15 at 21:13
  • 1
    On Mac OS I think the recommendation is to use `-d lldb` instead of `-d gdb` but [this StackOverflow question](http://stackoverflow.com/questions/11504377) (found by searching for your error message!) might help. – Martin Morgan May 20 '15 at 22:40