R Code Hub
tidyverse · ggplot2 · sf · terra · lme4 · survey — research-grade scriptsR Code Library — Ready-to-Run Recipes
4 ready-to-run snippet(s) · curated with sample data, dataset sources & use cases
ggplot2 — Trend with Confidence Band
Loess-smoothed line with 95% CI ribbon across a time series.
Visualizing yearly indicators (temperature, prices, indicators).
R beginners, social science researchers.
trend.csv · csv
year,value 2015,32.1 2016,33.0 2017,33.5 2018,33.9 2019,34.4 2020,34.0 2021,34.8 2022,35.2 2023,35.7 2024,36.0
library(tidyverse)
df <- read_csv('trend.csv')
ggplot(df, aes(year, value)) +
geom_point(size = 2, colour = '#2563eb') +
geom_smooth(method = 'loess', se = TRUE, colour = '#dc2626', fill = '#fecaca') +
labs(title = 'Annual Trend', x = NULL, y = 'Value') +
theme_minimal(base_size = 13)- Trend chart with CI ribbon
sf — Buffer + Spatial Join
Buffer point features by 500 m and count overlapping facilities per buffer.
Accessibility analysis around schools, clinics, transit stops.
GIS analysts who prefer R over QGIS scripting.
library(sf); library(dplyr)
pts <- st_read('points.geojson')
fac <- st_read('facilities.geojson')
buf <- st_buffer(st_transform(pts, 3857), 500) |> st_transform(4326)
joined <- st_join(buf, fac, join = st_intersects)
result <- joined |> group_by(id) |> summarise(n_facilities = n())
st_write(result, 'buffer_counts.geojson', delete_dsn = TRUE)- buffer_counts.geojson with facility counts
terra — NDVI & Zonal Stats
Compute NDVI from a Landsat stack and extract mean NDVI per admin polygon.
Per-district vegetation monitoring; agro-meteorological reports.
Researchers who prefer terra over rgdal/raster.
library(terra)
img <- rast('landsat.tif') # bands: B1..B7
ndvi <- (img[['B5']] - img[['B4']]) / (img[['B5']] + img[['B4']])
adm <- vect('districts.geojson')
zonal_mean <- extract(ndvi, adm, fun = mean, na.rm = TRUE)
write.csv(zonal_mean, 'ndvi_by_district.csv', row.names = FALSE)
plot(ndvi); plot(adm, add = TRUE, border = 'white')- NDVI raster plot
- ndvi_by_district.csv
survey + svyglm — Logistic Regression on DHS
Survey-weighted logistic regression with stratification & cluster sampling.
Modeling odds of stunting / contraceptive use / vaccination from DHS microdata.
Epidemiologists, demographic researchers.
library(haven); library(survey)
d <- read_dta('BDIR81FL.DTA')
d$wt <- d$v005 / 1e6
des <- svydesign(ids = ~v021, strata = ~v023, weights = ~wt, data = d, nest = TRUE)
fit <- svyglm(I(v201 > 3) ~ v012 + factor(v025) + v106, family = quasibinomial, design = des)
summary(fit)- Weighted logistic regression coefficients