Search code examples
rgitversion-controlenvironmentrenv

renv and git interaction R


I am trying to get better understanding how renv package in R works and how it interacts with git. Here are my questions

  1. Assume I have master and a couple git branches in my R projects for each (master and branches) I would like to use different environments (different libraries or different versions of the same libraries). Would renv be able to handle it, i.e. if I switch from one branch to another will need to call renv::restore().

  2. I have two separate projects with renv running in both of them, call them project A and project B. I would like to take environment from project B and replace environment in project A. How can I accomplish it? Do I just need to copy renv folder from one project to another?


Solution

  • Assume I have master and a couple git branches in my R projects for each (master and branches) I would like to use different environments (different libraries or different versions of the same libraries). Would renv be able to handle it, i.e. if I switch from one branch to another will need to call renv::restore().

    renv excludes the project library from version control (to avoid bloating the repository size), so in normally you would be required to restore the library path when switching branches.

    This is a bit arduous, so another solution would be to configure renv to use a different library path for each branch for your git repository. You could accomplish this with something like (in your project .Rprofile):

    branch <- system("git rev-parse --abbrev-ref HEAD", intern = TRUE)
    Sys.setenv(RENV_PATHS_LIBRARY = file.path("renv/library/branches", branch))
    

    This way, renv would be automatically configured to use a separate library for each branch, and this would happen automatically as you switch branches.

    This seems like something that would be useful to have in general; you might consider filing a feature request at https://github.com/rstudio/renv/issues if so.

    I have two separate projects with renv running in both of them, call them project A and project B. I would like to take environment from project B and replace environment in project A. How can I accomplish it? Do I just need to copy renv folder from one project to another?

    That should suffice, although it depends on how much of the environment you want to copy. The renv folder contains a settings.dcf file, defining project settings -- you may or may not want to copy those settings over as well. (See ?renv::settings for documention on renv's project-specific settings.)

    Alternatively, you could copy the project renv.lock from project B to project A, and then call renv::restore(). This might be more appropriate if you were e.g. copying a project from one machine to another, especially if those machines were running on different operating systems.