Read online
Reproducible R and Git Lab
Reproduce an analysis in R and Git
In this 25-minute lab, you’ll create a simulated dataset in base R, estimate the difference between two groups, and use Git to record a change to your analysis. You need R and Git, but no R packages, remote account, or real data.
1. Open a new project
Run these commands in a terminal. Then create a plain-text file called simulate.R in this folder and paste in the R script below.
mkdir statharbor-r-lab
cd statharbor-r-lab
git init
2. Simulate data and estimate the difference
The script simulates two independent groups with a true mean difference of 2 units. The sample difference will not usually equal 2 exactly. Welch’s two-sample t-test provides a confidence interval for the treated-minus-control difference, allowing for unequal group variances.
set.seed(241)
n <- 50L
true_difference <- 2
control <- rnorm(n, mean = 10, sd = 3)
treated <- rnorm(n, mean = 10 + true_difference, sd = 3)
fit <- t.test(treated, control, var.equal = FALSE)
result <- data.frame(
n_per_group = n,
true_difference = true_difference,
estimate = mean(treated) - mean(control),
lower_95 = unname(fit$conf.int[1]),
upper_95 = unname(fit$conf.int[2])
)
print(result, row.names = FALSE, digits = 3)
3. Run and record a checkpoint
Run the script twice without editing it. The output should match in the same R environment because the seed resets the random number generator. Then stage just the script and commit it. If Git asks for a name and email, configure your preferred Git identity before committing. A local commit does not send files anywhere.
Rscript --vanilla simulate.R
Rscript --vanilla simulate.R
git status --short
git add simulate.R
git diff --cached
git commit -m "Add reproducible two-group simulation"
4. Exercise: change one assumption
Change n <- 50L to n <- 200L. Before running the script again, predict what will happen to the confidence interval width. Compare the two widths (upper_95 minus lower_95). A larger sample typically narrows the interval under the same model, but the observed estimate need not get closer to 2 in this particular run. Review the change before recording it.
Rscript --vanilla simulate.R
git diff -- simulate.R
git add simulate.R
git commit -m "Increase sample size to study precision"
git log --oneline -2
5. What Git and a seed do not capture
Git records the files you commit, not your R installation. A seed controls randomness; it does not guarantee identical results across every R version or platform. Record R.version.string and sessionInfo() for future users. If you add packages, record their versions or adopt a lockfile. If you later share the project on GitHub, start by reviewing every tracked file; never commit credentials or identifiable data.