Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R `use(library, function)` a second time

Related to : Why might one load a library more than once in an R script?

Now, usually, with a complete library import, it is a good idea that a library is not loaded a second time.

However, if my main code has loaded a library with just one or two functions inside the library (e.g., use("data.table", "fread")), and then later I want to call some function in my code that needs a different function from the same library (e.g., use("data.table", nafill)), then it would be useful to force the load of library functions that don't yet exist in the current environment. can this be done by hand?

(I know use is a fairly new function, but I like the fact that the namespace is becoming less polluted.)

like image 637
ivo Welch Avatar asked Jul 29 '26 07:07

ivo Welch


1 Answers

Just create a simple wrapper:

use("data.table", "fread")
ls("package:data.table")
#[1] "fread"

use("data.table", "nafill")
ls("package:data.table")
#[1] "fread"

useplus <- function(package, include.only) {
  loaded <- ls(sprintf("package:%s", package), all.names = TRUE)
  unloadNamespace(package)
  if (missing(include.only)) {
    use(package)
  } else {
    use(package, union(loaded, include.only))
  }
}

useplus("data.table", "nafill")
ls("package:data.table")
#[1] "fread"  "nafill"
like image 99
Roland Avatar answered Jul 30 '26 23:07

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!