I have a multiple versions of the same package foo
(all with one function bar
), that I all want to use in the same script.
Following this question, I can load v1
of the package with library("foo", lib.loc = "pkgs/v1")
. But this loads all of the functions from the package.
Now I want to assign foo::bar
from the version v1 to bar_v1
and foo::bar
from version v2 to bar_v2
to call them independently. But I do not see the option to only load one function of the library given a lib location (eg a solution would be to specify a lib.loc
in the function call bar_v1 <- foo::bar
).
Is this possible in R?
MWE
I have created a test package here github.com/DavZim/testPkg, which has one function foo
which prints the package version (hard coded). The package has two releases, one for each version.
To get the tar.gz files of the package, you can use this
# Download Files from https://github.com/DavZim/testPkg
download.file("https://github.com/DavZim/testPkg/releases/download/v0.1.0/testPkg_0.1.0.tar.gz", "testPkg_0.1.0.tar.gz")
download.file("https://github.com/DavZim/testPkg/releases/download/v0.2.0/testPkg_0.2.0.tar.gz", "testPkg_0.2.0.tar.gz")
Then to setup the folder structure in the form of
pkgs/
0.1.0/
testPkg/
0.2.0/
testPkg/
I use
if (dir.exists("pkgs")) unlink("pkgs", recursive = TRUE)
dir.create("pkgs")
dir.create("pkgs/0.1.0")
dir.create("pkgs/0.2.0")
# install the packages locally
install.packages("testPkg_0.1.0.tar.gz", lib = "pkgs/0.1.0", repos = NULL)
install.packages("testPkg_0.2.0.tar.gz", lib = "pkgs/0.2.0", repos = NULL)
Now the question is what do I write in myscript.R
?
Ideally I would have something like this
bar_v1 <- some_function(package = "testPkg", function = "foo", lib.loc = "pkgs/0.1.0")
bar_v2 <- some_function(package = "testPkg", function = "foo", lib.loc = "pkgs/0.2.0")
bar_v1() # calling testPkg::foo from lib.loc pkgs/0.1.0
#> [1] "Hello World from Version 0.1.0"
bar_v2() # calling testPkg::foo from lib.loc pkgs/0.2.0
#> [1] "Hello World from Version 0.2.0"
Non-working Try
Playing around with it, I thought something like this might work. But it doesn't...
lb <- .libPaths()
.libPaths("pkgs/0.1.0")
v1 <- testPkg::foo
v1()
#> [1] "Hello from 0.1.0"
.libPaths("pkgs/0.2.0")
v2 <- testPkg::foo
v2()
#> [1] "Hello from 0.1.0"
.libPaths(lb)
v1()
#> [1] "Hello from 0.1.0"
v2()
#> [1] "Hello from 0.1.0" #! This should be 0.2.0!
Interestingly, if I swap around the versions to load 0.2.0 first then 0.1.0, I get this
lb <- .libPaths()
.libPaths("pkgs/0.2.0")
v1 <- testPkg::foo
v1()
#> [1] "Hello from 0.2.0"
.libPaths("pkgs/0.1.0")
v2 <- testPkg::foo
v2()
#> [1] "Hello from 0.2.0"
.libPaths(lb)
v1()
#> [1] "Hello from 0.2.0"
v2()
#> [1] "Hello from 0.2.0"