Working with git from R using usethis

By Bas Machielsen

September 26, 2020

Introduction

This post serves as a reminder and introduction into the usethis package, which provides an interface (and sometimes, a guide) to efficiently working with git from within R. We suppose that git (a version control system) is already installed on your system. The workflow should not vary between operating systems.

Packages like blogdown or hugodown often allow the user to create a folder, with lots of auxilary and supplementary files and an appropriate structure to ensure things work as they’re supposed to. The usethis package allows us to push everything to a newly-created git repository, provided we have done some initial set-up work (which is nevertheless very simple).

Set-up

You have to set-up a Github personal access token, which allows you to subject your work to version control securely from within R. Basically, what you do is, you run:

usethis::browse_github_token()

This launches a link in your browser, you enter your usernames/password, and you find yourself right in the middle of making a personal access token. The command also provides you with the instructions on where to leave it:

usethis::edit_r_environ()

and you paste your github access token. So far the set-up.

Work

Suppose now you start working from an R project, for example, a website generated by blogdown or a book generated by the bookdown package. Alternatively, consider you have just done your first work on a project in the form of a few scripts and analysis, and you make a new folder. (In this case, make sure to set your working directory to the folder where you want the git repository to be!)

First, you use usethis::use_git() to make your folder into a git repository. A good idea is to use usethis::git_vaccinate() to automatically make a .gitignore and add some tedious files to it.

Second, you use usethis::use_github() to initialize a GitHub repository (this works through your personal access token), and push all files to Github under an initial commit.

Conclusion

Then, you are ready to go. You can continue to use RStudio’s interface to git, or use the command line instead. This post is primarily intended for myself, to keep track of the order in which I run use_git and use_github(), but I hope it helps anyone who comes across similar issues.

Posted on:
September 26, 2020
Length:
2 minute read, 374 words
See Also: