How to Install R Packages from GitLab

How to Install R Packages from GitLab

Unless you are living under a rock, you have heard Microsoft's acquisition of GitHub. Not everyone is happy with Microsoft's move. Hence, quite a few open source projects started to move away from GitHub.

This move certainly is in favour of GitLab. GitHub imports at GitLab.

Installing R packages from GitHub has always been very easy thanks to devtools() package written by Wickham et al. For example, if you want to install the development version of devtools() all you have to do is

devtools::install_github("r-lib/devtools")

I have always been a big fan of GitLab. They allow unlimited private repositories which is perfect for me because I do not need my bad coding practices out in the wild.

Now that quite a few people are moving to GitLab, you might be wondering how you will be installing an R package from GitLab. Well, it is pretty easy actually. It is very similar to GitHub. You only need to get the HTTPS URL of the public repository and in R you use install_git().

url <- "https_url_of_the_package"
devtools::install_git(url = url)

Here is another tip. If you want to install an R package from a private repository, first, you need to set an SSH authentication in GitLab by adding your SSH keys. Then do the following.

creds <- git2r::cred_ssh_key(public = "~/.ssh/id_rsa.pub",
                             private = "~/.ssh/id_rsa", 
                             passphrase = passphrase)
url <- "ssh_url_of_the_package"
devtools::install_git(url = "ssh_url_of_the_package", credentials = creds)

You can specify a specific branch of the repository as well. In that case, just add branch="branch_name" to install_git options. Otherwise, install_git() will always default to the master branch. If you want to install the package into a specific library, you need to use withr::with_libpaths(). Here is an example.

lib_loc <- "location_of_the_library"
url <- "ssh_url_of_the_package"
creds <- git2r::cred_ssh_key(public = "~/.ssh/id_rsa.pub",
                             private = "~/.ssh/id_rsa", 
                             passphrase = passphrase)
withr::with_libpaths(new_lib_path, devtools::install_git(url = url,
                                                    branch = "development",
                                                    credentials = creds))

Easy peasy :)