How to create "locked" environment for testing things in R

Viewed 43

I know this it at the edge of being/not being a coding question, but I still try my luck.

When creating my own R package, I want to test it in a certain "simulated" user environment (environment in the sense of packages installed etc., not in the R sense of e.g. global environment), i.e. I want to create an RStudio project where I install a few default packages, e.g. the tidyverse and then I will test my package in that environment. However, when closing the project and opening again, I want it to be restored to whatever I defined as the default, which means:

  • additional packages I installed should not be there anymore
  • changes to the Rprofile or Renviron file should be reverted

One example why I need to do this is that in my package I retrieve an API key from Google and store it in the .Renviron file. However, once it is stored there, I can't test "first time usage" anymore. I could go into the .Renviron file, delete the API key and test again, but that's very tedious. Same with installed packages.

I thought that the renv package is there for exactly this purpose, but that doesn't seem to be the case. I.e. renv just keeps track of whatever settings I do in my project, but it doesn't let me use a certain default environment I defined.

Am I missing sth. in renv (I saw that it has a revert function, but it only works if I'm using my project with a git repository)? What would be a good way to define such a fixed environment (except going all the way down to a VM or kiosk setup in the OS)?

1 Answers

Since you want to isolate the OS, you need to create virtual machines, which can be easily reset. You can use vagrant to automatize this. If you define OS e.g. as just Linux distribution, you can also use different docker containers for testing your package.

For the latter case, create a Dockerfile based on rocker and use RStudio package manager to install prerequisites, e.g. tidyverse of a particular date. Your package files located in directory your_package can be copied to the docker image:

FROM rocker/r-ver:4.1.0
RUN R -e "install.packages('tidyverse', repos='https://packagemanager.rstudio.com/all/__linux__/focal/2022-04-25+Y3JhbiwyOjQ1MjYyMTU7QjA3OUM2Q0I')"
COPY your_package your_package
CMD Rscript your_package/test.R

Then you can build and run this image to test your package in an isolated environment, where only the Linux kernel is reused from the host.

Related