www.flickr.com


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)
   closure("x")
   print(y);
})
print(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. 



1 TrackBacks

Listed below are links to blogs that reference this entry: A SaneR R.

TrackBack URL for this entry: http://findingscience.com/mt/mt-tb.cgi/175

working on making a library for R to make it act more sane (like Ruby): http://findingscience.com/blog/2010/01/a-saner-r.html Read More

1 Comments

I have found that if you don't give your variables closure, they tend to get depressed, even to the point of ceasing all iterative activities.

Leave a comment

About this Entry

This page contains a single entry by bmuller published on January 14, 2010 11:23 AM.

New (Office) Digs was the previous entry in this blog.

New Job, Digs, and Deck is the next entry in this blog.

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.