January 2010 Archives

A SaneR R

| | Comments (1) | TrackBacks (1)
I've been working on a number of projects recently in R and find it fairly frustrating. There's no way to modify a variable in a function (as in the case of languages that support closures). This makes it especially hard for a language like R that has pretty good functional programming support.

I'm currently working on a library to make R act more sanely (called SaneR - I'll post again when I make it available online).  One function that I've found quite useful lately is one I call "closure":

closure <- function(..., frame=3) {
  parent <- parent.frame()
  frame <- ifelse(frame=="sapply", 4, frame)
  grandparent <- sys.frame(sys.nframe()-frame)
  for(name in c(...))
    assign(name, get(name, envir=parent), envir=grandparent)

Using this function you can affect variables outside of a function's scope.  For instance:

x <- 0
lapply(list(1,2,3,4,5), function(y) {
   x <- x + 1
   message("Run number ", x)

By calling closure() the variable x is set in the parent (actually, grandparent's) environment, meaning that by the time you reach the print statement x is 5.  This is great for things like counters within lapply. 

Other things that are going into the SaneR packages are:
  • a doTimes like Ruby's <int>.times { } method that does something some number of times and returns the results (like calling a map function to an integer range)
  • A foreach that can handle lists sanely.  For instance, if you want to do something for every name and value in a list, it takes more lines of code then it should.
  • A propper logging mechanism for long running tasks.  A whole lot of R tasks take a while to run (R is slow).  I'm writing a logging class that can print out the % complete for some task as well as an estimate to time of completion.
  • and more....
If there are any more ideas out there, comment on this post. 

About this Archive

This page is an archive of entries from January 2010 listed from newest to oldest.

November 2009 is the previous archive.

March 2010 is the next archive.

Find recent content on the main index or look in the archives to find all content.

Creative Commons License
This weblog is licensed under a Creative Commons License.