3

Short version: I'm working on an R package, and I currently have a stable version. I have some updates to make, and would like to compare the updated version of the code to the stable version in the same R environment. How do I do this?

I'm new to package development, and I suspect dev_mode is helpful here, but ?dev_mode hasn't helped me.

Long version: Here's the main problem I have... Inside the package (let's call it somePackage) I have a function

foo <- function(x){
    y <- bar(x) # some other function defined inside my package
    y
}

If I simply duplicate somePackage in a separate directory to make a development version, then load both, R now sees two copies of bar, which creates a conflict. I cannot run both versions of foo and bar in the same R environment.

If I only had the one function, I could probably do something like somePackage::bar and somePackage_dev::bar, but in reality I have dozens of functions in somePackage and making these changes would be tedious and should be unnecessary.

The key thing here is needing to run BOTH versions of foo in the same environment so that I can quickly and easily compare the timing and output of both versions on identical inputs.

JohnA
  • 321
  • 2
  • 11

1 Answers1

4

You can achieve this by loading package namespaces into environments and then attaching and detaching them. You can see my answer here for more about this strategy. But basically, you can do as you say and then load the namespace for both versions with something like:

x <- loadNamespace('somePackage')
y <- loadNamespace('somePackage_dev')

This loads the package name spaces into the environments x and y without attaching them to the search path. Then you can just attach and detach to decide which version of the package you want to work with in the global environment.

Here's a trivial example of how this would work (just imagine a is a function from your package rather than a constant):

> x <- new.env()
> y <- new.env()
> search()
 [1] ".GlobalEnv"        "package:stats"     "package:graphics" 
 [4] "package:grDevices" "package:utils"     "package:datasets" 
 [7] "package:devtools"  "package:methods"   "Autoloads"        
[10] "package:base"     
> x$a <- 1
> y$a <- 2
> a
Error: object 'a' not found
> x$a
[1] 1
> y$a
[1] 2
> attach(x)
> search()
 [1] ".GlobalEnv"        "x"                 "package:stats"    
 [4] "package:graphics"  "package:grDevices" "package:utils"    
 [7] "package:datasets"  "package:devtools"  "package:methods"  
[10] "Autoloads"         "package:base"
> a
[1] 1
> detach(x)
> a
Error: object 'a' not found
> attach(y)
> search()
 [1] ".GlobalEnv"        "y"                 "package:stats"    
 [4] "package:graphics"  "package:grDevices" "package:utils"    
 [7] "package:datasets"  "package:devtools"  "package:methods"  
[10] "Autoloads"         "package:base" 
> a
[1] 2
> detach(y)
> a
Error: object 'a' not found
Community
  • 1
  • 1
Thomas
  • 43,637
  • 12
  • 109
  • 140