How to use git in RStudio

Git can also be used directly within RStudio, meaning the command line can be avoided (if you wish!) for daily use. To get started, you’ll need to have git, R (https://www.r-project.org/) and RStudio (https://www.rstudio.com/products/rstudio/download/) installed. Whilst this option works particularly well for R/coding projects, it can still be used for any type of file or group of folders.

Key steps to get started are:

  1. On Gitlab (or Github): create your new online repository
  2. Within RStudio: click File - New Project - Version Control - Git
  3. On Gitlab: click Clone and copy the relevant URL for your repo (use HTTPS if you haven’t set up SSH)
  4. Within RStudio: paste this URL into Repository URL and choose where to store the repo on your PC
  5. Within RStudio: click Create Project

You may also be prompted for your Gitlab/Github username/password. Your local repo should now be set up on your PC. This will be set up as an R project (https://r4ds.had.co.nz/workflow-projects.html)- this is helpful for cloning/using on multiple computers where all file location paths are relative (not absolute).

To use git within RStudio:

  1. Make changes to files and folders within your local repo.
  2. As you make changes, these will appear in the Git tab in RStudio (next to Environment, History, etc.)
  3. Different symbols indicate different changes, e.g.:
    • Yellow question mark: You’ve added a new file that git hasn’t tracked yet
    • Blue M symbol: You’ve modified a file
    • Red D symbol: You’ve deleted a file
  4. You can use Diff to see how each file has changed
  5. To stage a commit, tick the boxes next to file(s) you would like to include in the commit, and click Commit. Add text to describe your commit in the Commit message box and press Commit.
  6. You can then Pull (blue down arrow) to check for remote changes to the online repo, and Push (green up arrow) to send your commits to the online repo.

More information is available at https://happygitwithr.com/rstudio-git-github.html and https://jennybc.github.io/2014-05-12-ubc/ubc-r/session03_git.html.

Top tip (for any git work):

Generally you shouldn’t track extra output files that are generated automatically on each computer (e.g. R project files, R history). Within the main folder of your repo, consider including a text file called .gitignore.txt which includes a list of file types (or specific files/folders) you wish not to track or upload to your repo. Lots of example templates are available (https://github.com/github/gitignore; see R.gitignore for the R example), and check that you include *.Rproj. Note: this file, and any changes to it, should be committed to your repo.