rimportnamespacesinclude

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.)


Solution

  • 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"