Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent R from loading a package?

Tags:

package

r

I am using the multicore package in R for parallelizing my code. However, if the tcltk package is loaded, forking processes with the multicore package will cause R to hang indefinitely. So I want to prevent tcltk from ever loading. I want an immediate error if any package tries to load it as a dependency. Is this possible?

Alternatively, can I unload a package after it has been loaded?

like image 928
Ryan C. Thompson Avatar asked Apr 03 '12 18:04

Ryan C. Thompson


2 Answers

If immediately detaching the package after it's been attached is a good enough solution, then try something like the following:

setHook(hookName = packageEvent("tcltk", "attach"),
        value =  function(...) detach(package:tcltk))

# Try it out
library(tcltk)
# Loading Tcl/Tk interface ... done
# Error in as.environment(pos) : invalid 'pos' argument
search()
# [1] ".GlobalEnv"        "package:graphics"  "package:grDevices"
# [4] "package:utils"     "package:datasets"  "package:methods"  
# [7] "Autoloads"         "package:base"     

If (as seems likely) the very act of loading & attaching the package is causing the problem, you might also pursue a strategy like the one sketched out in the comments to your question. Namely:

  1. Create a harmless dummy package, also named tcltk
  2. Place it in a directory named, e.g., "C:/R/Library/dummy/".
  3. Before running any other commands, prepend that directory to .libPaths by executing .libPaths(c("C:/R/Library/dummy/", .libPaths())).

Then, if any package attempts to load tcltk, it will first look for packages in "C:/R/Library/dummy/", and, finding one of that name, will load it for a moment (before it's immediately detached by the hook described above).

like image 110
Josh O'Brien Avatar answered Sep 26 '22 07:09

Josh O'Brien


Another way to avoid loading a particular package as a dependency is, based on the assumption that none of the functions you require depend on that package, would be to reference the functions you need using their namespace:

lattice::xyplot(1~1)

This way, you don't need to load the package with your function, and you don't inadvertently load the problem package.

like image 31
BenBarnes Avatar answered Sep 26 '22 07:09

BenBarnes