Loops and programming

Start with the expanded example for each command. Open the variants for options and alternative R approaches. Read the qualifications before adapting the code.

ado

Update installed packages

Stata

ado update

R Package:utils

update.packages()

capture

Run code and report success instead of stopping

Stata

capture command

R Package:tidystata

capture(expression)

capture() returns TRUE or FALSE. Use try() to keep the error message.

clear

Remove every object

Stata

clear all

R Package:base

rm(list = ls())

Restarting R (Session > Restart R in RStudio) gives a truly clean start.

cls

Clear the console

Stata

cls

R Package:base

cat("\014")

In RStudio, Ctrl+L does the same.

display

A stored coefficient

Stata

display _b[x]

R Package:stats

coef(fit)["x"]

A stored standard error

Stata

display _se[x]

R Package:stats

sqrt(diag(vcov(fit)))["x"]

ereturn

Model statistics

Stata

ereturn list

R Package:broom

broom::glance(fit)

broom::tidy(fit) gives the coefficient table, and names(fit) lists every stored part.

foreach

Same calculation for several variables

Stata

foreach v of varlist v1-v5 { generate `v'_sq = `v'^2 }

R Package:dplyr

mutate(data, across(v1:v5, ~ .x^2, .names = "{col}_sq"))

across() replaces most variable loops; for other loops R has for (v in names) { … }.

forvalues

Loop with a condition

Stata

forvalues i = 1/5 { generate v`i'_sq = v`i'^2 if v`i' > 0 }

R Package:dplyr

mutate(data, across(v1:v5, ~ if_else(.x > 0, .x^2, NA), .names = "{col}_sq"))

Loop over variables numbered in their names

Stata

forvalues i = 6/10 { forvalues j = 3/5 { replace x_`i'_`j' = x_`i'_`j' + 1 } }

R Package:dplyr

mutate(data, across(matches("^x_([6-9]|10)_[3-5]$"), ~ .x + 1))

A regular expression picks the names. varlist(“x_[6-10]_*“) works when only one number range is needed.

frame

Hold another dataset

Stata

frame create other

R Package:tibble

other <- tibble()

R keeps any number of data frames as separate objects, so frames are built in.

if

Run code only if a condition holds

Stata

if `x' > 0 { display "positive" }

R Package:base

if (x > 0) print("positive")

Quote it: findit(“if”), because if is a reserved word in R.

local

Store a list of variable names

Stata

local vars x1 x2 x3

R Package:base

vars <- c("x1", "x2", "x3")

Use it with all_of(): select(data, all_of(vars)) or across(all_of(vars), …).

macro

List defined objects

Stata

macro list

R Package:base

ls()

matrix

Create a matrix

Stata

matrix A = (1, 2 \ 3, 4)

R Package:base

A <- matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE)

preserve

Keep a copy to return to

Stata

preserve

R Package:base

backup <- data

R never changes data in place, so keep the original object and assign results to a new name; restore is data <- backup.

program

Write your own command

Stata

program define myprog

R Package:base

myprog <- function(data) { summ(data) }

quietly

Run without printing

Stata

quietly regress y x

R Package:stats

fit <- lm(y ~ x, data = data)

Assigning a result never prints it; print(fit) or summary(fit) shows it later.

return

See the results a command stored

Stata

return list

R Package:tidystata

str(summ(data, x))

R results are ordinary objects: assign them and pick out parts, as in s <- summ(data, x); s$mean.

scalar

Store a single number

Stata

scalar a = 3

R Package:base

a <- 3

set

Make random numbers reproducible

Stata

set seed 2024

R Package:base

set.seed(2024)

Differs from Stata set_seed(.fn, seed) sets the seed inside a pipe; see the sample rows. R and Stata use different random-number streams; the same numeric seed does not reproduce the same draws or selected rows.

Find where an error happened

Stata

set trace on

R Package:base

traceback()

debug(f) or browser() steps through a function line by line.

tempfile

A temporary file

Stata

tempfile f

R Package:base

f <- tempfile(fileext = ".rds")

Temporary variables are not needed: intermediate columns can be dropped, or kept as separate objects.

timer

Time how long code takes

Stata

timer on 1

R Package:tidystata

timer(expression)

version

Version control

Stata

version 18

R Package:base

R.version.string

renv::snapshot() records package versions so a project can be reproduced later.

which

Where a command comes from

Stata

which summarize

R Package:utils

getAnywhere("summ")

while

Repeat while a condition holds

Stata

while `i' < 10 { local i = `i' + 1 }

R Package:base

while (i < 10) { i <- i + 1 }