R tips: Determine if function is called from specific package
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
I like the “multicore” library for a particular task. I can easily write a combination of if(require("multicore",...))
that means that my function will automatically use the parallel mclapply()
instead of lapply()
where it is available. Which is grand 99% of the time, except when my function is called from mclapply()
(or one of the lower level functions) in which case much CPU trashing and grinding of teeth will result.
So, I needed a function to determine if my function was called from any function in the “multicore” library. Here it is.
First define a generally useful function:
is.in.namespace <- function (ns) { for ( frame in seq(1, sys.nframe(), 1) ) { fun <- sys.function(frame); env <- environment(fun) n <- environmentName(env) if ( n == ns ) return(TRUE); } return(FALSE); }
Then we use it for our purpose:
is.in.multicore <- function (...) { return(is.in.namespace("multicore")) } library("multicore") stopifnot( mclapply(as.list(1), is.in.multicore)[[1]] == TRUE ) stopifnot( lapply(as.list(1), is.in.multicore)[[1]] == FALSE ) stopifnot( local( {mclapply <- function(x) return(x); mclapply(is.in.multicore())} ) == FALSE )
Easy when you know how.
Jump to comments.
You may also like these posts:
-
A warning on the R save format
The save() function in the R platform for statistical computing is very convenient and I suspect many of us use it a lot. But I was recently bitten by a “feature” of the format which meant I could not recover my data. I recommend that you save data in a data format (e.g. CSV or CDF), not using the save() function which is really for objects (data and code). What is your approach?
-
R: Eliminating observed values with zero variance
I needed a fast way of eliminating observed values with zero variance from large data sets using the R statistical computing and analysis platform . In other words, I want to find the columns in a data frame that has zero variance. And as fast as possible…
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.