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":
Other things that are going into the SaneR packages are:
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) {Using this function you can affect variables outside of a function's scope. For instance:
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)
}
x <- 0By 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.
lapply(list(1,2,3,4,5), function(y) {
x <- x + 1
message("Run number ", x)
closure("x")
print(y);
})
print(x)
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....