7

Is there a way code in an R package can find out which package or namespace it belongs to?


Background: I find I have common code between packages that just differs in the package name. One common example is tests/testthat.R:

library(testthat)
library(ShiftedExcitation)

test_check("ShiftedExcitation")

If the code could find out to which package or namespace it belongs, I could avoid a number of places where the package name is now given.


Right now I define a hidden variable that contains the package name, say

.PKG <- "ShiftedExcitation"

and then use something along the lines of *

library(testthat)
library(.PKG, character.only = TRUE)

test_check(.PKG)

but I'm curious whether a more elegant solution exists.

* I did not get this working so far as testthat.R is evaluated outside the package namespace. It does work for defining a unittest function inside the package code, though.

cbeleites unhappy with SX
  • 13,717
  • 5
  • 45
  • 57
  • You might be able to use `.getNameSpace(match.call()[[1]])` which grabs the function's name as argument. possibly helpful: http://stackoverflow.com/questions/15595478/how-to-get-the-name-of-the-calling-function-inside-the-called-routine – Carl Witthoft Sep 11 '15 at 14:08
  • `getNamespaceName(topenv())` ? E.g., `debug(lm); lm(); getNamespaceName(topenv())` – Martin Morgan Sep 11 '15 at 15:06
  • @MartinMorgan: `topenv` is almost the answer - just that the `testthat` namespace can be before the pacakge in the `search ()` path. – cbeleites unhappy with SX Sep 11 '15 at 16:56

1 Answers1

0

Approaching an answer:

@MartinMorgan's hint to use topenv () is quite close. But it turns out that while running unit tests with testthat, testthat is before the package namespace in the search path.

So this is the current state:

.findmyname <- function() {
    pkgs <- .packages ()

    if (pkgs [1] == "testthat")
        pkgs [2]
    else
        pkgs [1]
}

This function finds the name of the package in question both from within the package and in tests/testthat.R. (Of course, any .findmyname () defined within the package is not known in tests/testthat.R before the library call...)

cbeleites unhappy with SX
  • 13,717
  • 5
  • 45
  • 57