Lecture 5.3: Managing Data for Reproducibility: Git I
AREC 570 / ECON 530 / Unit 5
Reading and today’s path
Gentzkow and Shapiro, Code and Data for the Social Sciences , Sections 1–4 (Gentzkow and Shapiro 2014 )
Bryan, Excuse Me, Do You Have a Moment to Talk About Version Control? , 2017 (Bryan 2017 )
Organize a project so another researcher can follow it
Identify where undocumented memory enters the workflow
Set up Git, GitHub, and RStudio
Take one research project from its first commit through GitHub
Choose a workflow for team projects and public repositories
Reproducibility starts with organization
Can another researcher reconstruct a result from the same inputs?
They need
Original inputs
Code for every transformation
The order in which the code runs
Software and package requirements
The project version used for the result
Source: Gentzkow and Shapiro (2014 )
Start with a recognizable project root
research_project/
README.md
research_project.Rproj
run_all.R
code/
data/
output/
docs/
lab_diary.md
The .Rproj file opens this folder as the project root
Separate files by function
code/ scripts and reusable functions
data/raw/ source files as retrieved
data/derived/ files constructed from source data
output/figures/ figures produced by code
output/tables/ tables produced by code
docs/ codebook and project documentation
Raw inputs remain unchanged. Scripts rebuild derived data and outputs
Paths should travel with the project
Use paths relative to the project root
read.csv ("data/raw/streamflow.csv" )
A path beginning with one person’s user directory usually fails on another computer
read.csv ("C:/Users/jane/Desktop/streamflow.csv" )
Automate the sequence
run_all.R records the order of operations
source ("code/00_setup.R" )
source ("code/01_get_cdl.R" )
source ("code/02_get_streamflow.R" )
source ("code/03_get_weather.R" )
source ("code/04_get_acs.R" )
source ("code/05_build_daily.R" )
source ("code/06_outputs.R" )
One command rebuilds the project from documented inputs
Where does memory enter the workflow?
Consider one result in your current research project
Which steps happen through code
Which steps happen through menus or manual edits
Where the order of operations is recorded
Which inputs can change over time
What another researcher would need to ask before running it
Documentation replaces memory
Different records answer different questions
Scripts and run_all.R
What operations produced the result
README
How should a new researcher run the project
Codebook
What do the variables and values mean
Retrieval log
Where and when did the inputs originate
Lab diary
Why did the researcher make a decision
Version history
What changed across project states
What version control adds
Version control gives a project a documented history. At selected points, it records the state of the project’s files together with the author, date, and reason for the change.
That history allows a researcher to compare versions, recover earlier work, and identify the exact project state used for an analysis or manuscript.
Git, GitHub, and RStudio have different roles
Git
Software that records the history of a project on your computer
GitHub
An online service that hosts a copy of a Git project and supports sharing
RStudio
An editor that lets you work with project files and run Git through buttons, menus, and the Terminal
A Git project can remain entirely on one computer. GitHub adds an online copy. RStudio calls Git commands on your behalf (Bryan 2017 )
One project can exist in three locations
Walk from left to right. Saving changes the working files. Committing records a checkpoint in local Git history. Pushing copies local commits to GitHub. Pulling brings commits from GitHub into the local repository.
Version control vocabulary
Repository
A project and its Git history
Working directory
The files currently visible in the project folder
Tracked file
A file whose changes Git follows
Staging area
The changes selected for the next commit
Commit
A recorded checkpoint in the project history
Diff
The lines added, removed, or changed
Version control vocabulary
Commit message
A short explanation attached to a commit
Tag
A fixed readable name for a selected commit
Local
The repository on your computer
Remote
A connected repository hosted online
Main
The conventional name for the project’s primary branch
Push
Send local commits to a remote
Pull
Bring remote commits into the local repository
Saving, committing, and pushing are separate actions
Save writes the current file to the working directory
Commit records selected changes in the local Git history
Push sends local commits to GitHub
A saved file can remain uncommitted. A local commit can remain unpushed. Ask students where each action stores information.
One-time setup
Complete these steps once on each computer
Install Git
Create a GitHub account
Tell Git your name and email
Create a GitHub personal access token
Store the token for RStudio and Git
Verify the connection
The demo repository provides detailed instructions in docs/setup-rstudio.md
Step 1: install Git
Download Git from git-scm.com/downloads
Restart RStudio after installation, then, in your Console window, run
A successful check prints a version such as git version 2.55.0.windows.3
Steps 2 and 3: create accounts and identify yourself
Create an account at github.com
Install two helper packages and configure Git
install.packages (c ("usethis" , "gitcreds" ))
usethis:: use_git_config (
user.name = "Your Name" ,
user.email = "you@example.edu"
)
Use an email connected to your GitHub account
Steps 4 and 5: connect GitHub
Create a personal access token
usethis:: create_github_token ()
Copy the token from GitHub, then store it
Treat the token like a password. Keep it out of scripts, .Renviron, and commits
Step 6: verify the setup
Run
Check for
The expected Git version
Your name and email
A stored GitHub token
A recognized GitHub account
Pause for a live RStudio walkthrough. Open the Terminal to show git --version, then run usethis::git_sitrep() in the Console. Ask students to compare their output with the projected output.
Case 1: your own research project
You have an existing RStudio project with scripts, data documentation, and early results
Your goal is to
Review which files belong in Git
Initialize the local repository
Make the first commit
Create a private GitHub repository
Use the workflow during each research session
Start-to-finish workflow
Open the project in RStudio
Open the .Rproj file inside the project root
Confirm that
The project name appears in the upper-right corner
The Files pane begins at the project root
Relative paths run successfully
The project contains a README or equivalent instructions
Decide what Git should track
Track files that explain, run, or report the research
Source code
README files and project documentation
Data dictionaries and retrieval logs
Small configuration files without credentials
Manuscript and presentation source files
Generated outputs can follow the project team’s publication and archival policy
Use .gitignore for excluded files
Common exclusions include
API keys and credentials
Confidential or restricted data
Large source files stored in an archive
Derived files rebuilt by code
R session files such as .RData and .Rhistory
.gitignore applies to files Git has not started tracking
Check before the first commit
Open .gitignore and review every file in the project
Does any file contain a password or API key
Does the project contain restricted or licensed data
Is a large file available from a stable archive or reproducible download
Can a derived file be rebuilt by the project scripts
Does each tracked file help explain, run, or report the research
Revoke any credential that enters a commit because earlier commits retain its contents
Initialize the local repository
Run in the RStudio Console
RStudio may restart the project. A Git tab should then appear beside Environment and History
This command creates the hidden .git directory that stores local history
Git records changes through three states
Working directory
Files currently being edited
Staging area
Changes selected for the next commit
Commit
A recorded checkpoint with an explanatory message
Staging lets one work session become several coherent commits
Read the RStudio Git pane
M
A tracked file was modified
?
A new file is untracked
A
A new file is staged for its first commit
D
A tracked file was deleted
R
A tracked file was renamed or moved
Diff shows changed lines. The Staged boxes select changes for the next commit
Make the first commit
Open the Git pane
Select Diff and inspect the proposed files
Stage the files that belong in the repository
Enter Create initial project structure
Select Commit
The commit now exists in local Git history
Create the private GitHub repository
Run in the RStudio Console
usethis:: use_github (private = TRUE )
This command
Creates a GitHub repository under your account
Connects the local repository to the GitHub remote
Names that remote origin
Pushes the current branch and commits
main and origin name different things
main
Branch
The project’s primary line of commits
origin
Remote
The GitHub repository connected to the local project
Check the current branch and connected remotes in the RStudio Terminal
git branch --show-current
git remote -v
main appears as a branch. origin appears beside the GitHub URL used for pull and push
The everyday Git workflow
Pull before beginning a work session
Make one coherent change
Inspect the changed lines with Diff
Stage the files that belong to the change
Write a specific message and Commit
Push the commits to GitHub
Repeat the edit, inspect, stage, and commit steps as the work develops
Follow along in RStudio
In a practice project
Add one sentence to README.md
Save the file
Inspect the changed line with Diff
Stage README.md
Commit with Clarify project research question
Push the commit
Open GitHub and locate the same commit
Show each location after every action. After saving, point to the modified status in RStudio. After committing, show History. After pushing, refresh GitHub and open the commit.
The corresponding Git commands
git pull
git status
git diff
git add README.md
git diff --staged
git commit -m "Clarify project research question"
git push
The RStudio buttons run these commands
Companion reference: docs/git-in-rstudio.md
A diff shows what changed
- This project studies water use
+ This project studies how irrigation restrictions affect water use
The diff records the changed text
The commit message records the reason for that change
Clarify treatment and outcome in research question
Write messages for future readers
updates
Code suppressed ACS estimates as missing
fixed bug
Keep FIPS codes as text to preserve leading zeros
final version
Restrict sample to the April–September growing season
A useful message identifies the completed change. Add an explanation when a change alters the sample or interpretation
History makes earlier states inspectable
Use History in RStudio or Commits on GitHub to inspect
The files changed in a commit
The exact lines added and removed
The author and date
The commit message
The identifier for the checkpoint
Tags such as 5.2-retrieve give a readable name to a particular commit
What if you want to start from an existing repository?
A remote repository already exists when
A coauthor invites you to a team repository
You want your own linked copy of public work
You want to contribute a change to another repository
The starting action depends on ownership and purpose
Where we left off in Lecture 5.2
The arec_570_demo project retrieved land-use, streamflow, weather, and Census data through APIs
R scripts recorded the requests
Raw downloads preserved the responses
A retrieval log recorded source, date, and parameters
Follow-along repository
arec_570_demo develops in stages across Unit 5
5.2-retrieve
API collection
Retrieval script
5.3-structure
Structure and Git
Folders, run_all.R, and .gitignore
5.4-collaborate
Collaboration
Issues, branches, and pull requests
5.5-report
Reporting
Codebook, sample, and data section
Completed before class
Lecture 5.2 assigned Parts One and Two of docs/setup-rstudio.md
Install Git and restart RStudio
Create a GitHub account
Configure your Git name and email
Create and store a GitHub personal access token
Request, activate, and store a Census API key
Run usethis::git_sitrep() without errors
Confirm nzchar(Sys.getenv("CENSUS_API_KEY")) returns TRUE
Bring the laptop used to complete these steps
Vocabulary for shared repositories
Clone
A local copy of a remote repository and its history
Fork
A linked GitHub copy under your account
Lecture 5.4 will cover branches, merges, and pull requests
Choose how your local project begins
You have access to a team repository
Clone the team repository
You want a linked copy of public or course work
Fork , then clone your fork
Cloning is the step that creates the working project on your computer
Case 2: clone a team repository
Your advisor adds you to an existing private repository for a joint project
The team already shares one GitHub repository. You need a local copy containing the same files and history
Use clone when the repository already exists and you have permission to work in it
Clone the team repository in RStudio
In RStudio
Copy the repository’s HTTPS URL from Code
Select File > New Project > Version Control > Git
Paste the URL and choose a parent folder
Select Create Project
Cloning copies files and history, names the team repository origin, and usually opens its default branch, main
Case 3: fork public or course work
You want your own copy of the course repository and need to receive later course updates
Use fork when you want a linked GitHub copy under your account
A fork supports
Receiving later updates from the original repository
Developing changes in a repository you control
Proposing changes through a pull request
After creating the fork on GitHub, clone your fork to RStudio
Follow along: fork the demo
Open github.com/laurenchenarides/arec_570_demo while signed in
Select Fork
Clear Copy the main branch only so the lecture tags are included
Select Create fork
Confirm the address is github.com/your-username/arec_570_demo
Your fork remains linked to the course repository for later synchronization
Follow along: clone your fork
On your fork, select Code and copy the HTTPS URL
In RStudio select File > New Project > Version Control > Git
Paste the URL and choose a parent folder such as GitProjects
Select Create Project
Confirm the project name appears in the upper-right corner
Confirm a Git tab appears beside Environment and History
The local repository’s origin points to your fork
Origin, upstream, and main
Emphasize that main is a branch in each repository. origin and upstream identify repositories from the perspective of the local project. In this course, students use GitHub’s Sync fork action, so they do not need to configure a local upstream remote.
Read the three names in this exercise
main
Branch
The primary line of commits in each repository
origin
Local remote name
Your fork on GitHub
upstream
Fork relationship or remote name
The original course repository
Course updates: Sync fork updates your fork from the course repository. Pull then updates local main from origin
upstream appears in git remote -v only when configured as a second remote. Lecture 5.4 creates a separate branch and merges its commits into main
Which action fits the project?
A. Your advisor adds you to a private team repository
B. You want your own version of the course demo and need later course updates
Why synchronize local and remote history?
A commit initially exists only in the repository where it was created
Push makes local commits available on GitHub
Pull brings GitHub commits to the computer
Regular synchronization gives collaborators access to current work
Frequent pulls reduce the number of changes that must be reconciled later
Pull and push synchronize commits
Pull brings remote commits into the local repository
Push sends local commits to the remote repository
When GitHub reports newer remote commits
Pull the remote commits
Review any conflicts Git reports
Complete the merge if required
Push the combined history
Lecture 5.4 develops branches, conflicts, and pull requests
Common problems and first checks
The Git tab is missing
Confirm the .Rproj inside a Git repository is open
Git rejects a commit
Check the configured name and email with usethis::git_sitrep()
GitHub rejects authentication
Check whether the personal access token is present and current
A push is rejected
Pull and inspect the incoming commits
A file never appears in the Git pane
Check the patterns in .gitignore
Record the exact error message when asking for help
Apply the workflow to your research project
For one current project, identify
The project root
The command or script that reproduces the main result
The files Git should track
The files .gitignore should exclude
The people who need repository access
The next research decision that deserves a commit
Share one unresolved choice with the class
Return to Gentzkow and Shapiro
How do the reading’s recommendations appear in the demo repository?
Automation through run_all.R
Separate directories for code, raw data, derived data, and outputs
Relative paths from the project root
Version history for code and documentation
README files that describe execution and file roles
Which recommendation requires the largest change in your current workflow?
Before you leave
Confirm that your fork contains one new commit from today’s exercise
Be prepared to show
The line you changed
The commit message
The same commit in RStudio and on GitHub
One file your research repository should exclude
Summary
Project structure records where inputs, code, and outputs belong
Git records local changes as commits
GitHub hosts a remote repository for sharing and collaboration
RStudio provides an interface for editing files and using Git
Clone and fork describe different ways to begin from an existing repository
Pull, edit, inspect, stage, commit, and push form the everyday workflow