R bits

The purpuse of this is to include bits of useful R code. I'm calling this R bits beacause it does not even amount to R tips or tricks.


Profiling R Code

Profiling R code is given in the manuals here. Profiling compiled C code in an R package requires a bit more effort. It is easy with Shark on a Mac see post but it does not work out-of-the-box in Linux. At least it required some tweaking in Ubuntu and in a Fedora VM.

If, like me, you get an error when trying to generate a report

  $ opreport
  opreport error: No sample file found: try running opcontrol --dump or
  specify a session containing sample files 

This might be solved by specifying the directory. In Ubuntu...

  opreport --session-dir=/home/fernando
  -l /usr/local/lib/R/site-library/BioCro/libs/BioCro.so | head

Running R CMD BATCH 

I've been running R in batch mode for a while but didn't need to pass arguments to the call. Initially, I ran into some problems but here they are basically solved after googling around and trial and error. Here I show some things to keep in mind when running R in batch mode. First it is likely that you don't only need to run R in batch mode but also make it part of some shell script.  The first detail is that the arguments need to be in single quotes (this is not the way it is shown in the R manuals)

 R CMD BATCH '--args Arg1 Arg2' myScript.r output.Rout

However, If you want to make this part of some bigger shell script, use double quotes so that you can interpolate the argument

R CMD BATCH "--args $Arg1 $Arg2" myScript.r output.Rout

There is more material about this in the R website and in the R tips websites to the left

Storing arbitrary objects in an array

The last challenge I ran into when writing some R code was to store arbitrary objects in an array. I wanted to do this because a function was inside a loop but each time the loop run the resulting object was different so I needed a way of looking at all these objects. I needed this type of code because the object returned by my function had many components to it and it wasn't just a matter of storing numbers in a matrix. This approach also lets you store arbitrary objects in the array.

This is how this can be accomplished

n <- 10
arrMat <- array(list(),c(1,n))
for(i in 1:n){
obj <- myfun()
arrMat[[i]] <- obj
# Or arrMat[[i]] <- myfun() directly

Failry simple, but quite tricky at the same time.