Skip to contents

中文版

For chapter navigation, search and expandable alternatives, open the Stata to R Reference. The book has English and Chinese editions with a language switch on each chapter. This page remains available as the single-page reference.

If you know Stata, you already know what you want to do; the question is how to say it in R. This page lists Stata commands next to the R code that does the same job, using tidystata where it has a Stata-style function and the standard package everywhere else.

Look it up from the console

findit() searches the same list from R. Type one Stata word bare, or quote anything longer. Stata’s abbreviations work.

findit(reg)
#> # Linear regression [stats]
#> Stata: regress y x1 x2
#> R:     fit <- lm(y ~ x1 + x2, data = data)
#> # Note: summary(fit) shows the coefficient table; broom::tidy(fit) returns it as a data frame.
#> 
#> # 17 more examples. To see them all: findit(reg) |> print(n = Inf)
findit("merge 1:1 id, keep(match)")
#> # Keep matched rows only [dplyr]
#> Stata: merge 1:1 id using data2, keep(match)
#> R:     inner_join(data1, data2, by = "id")
#> # Note: dplyr retains overlapping non-key columns with suffixes instead of Stata master values, creates no _merge, and does not enforce a declared 1:1 key constraint.
#> 
#> # merge() [base]: Merge two data frames (base R)
#>   Related Stata: merge
#> 
#> # 17 more examples. To see them all: findit("merge 1:1 id, keep(match)") |> print(n = Inf)

You can also look up an R function (findit(left_join)) or ask a question (findit("how do I remove duplicate rows")). The console shows the best matches; the returned table contains all matches. Call findit() for the whole list. Descriptions follow R’s language setting; English and Chinese queries both work.

Comma-separated names customize compatible examples, such as findit(tab, sex, region). The default shows one preferred answer when the task is clear; findit(tab) |> print(n = Inf) shows all variants, selected alternative R approaches, qualifications and source links. Package-qualified lookups such as findit(dplyr::filter) distinguish functions with the same name.

This reference contains 514 command families, 181 Stata functions and 3 operators, with 1716 distinct Stata examples and 1782 paired R examples. Abbreviations and alternative R implementations do not increase the command count. The R index describes 949 function/package pairs.

Use the command tables

The tables cover tidystata and other R packages, including modelling, reshaping, survey analysis and graphics. For panel lags and leads, tidystata provides stata_lag(), stata_lead() and stata_diff(); specify the time column and use .by to identify panels.

The index is alphabetical; tables are grouped by subject and sorted by command, preferred answer and example. A package named beside a snippet is needed to run that snippet, but findit() itself does not load or install reference packages. The label names the primary package, rather than every helper dependency; the R function index identifies additional functions and their packages.

A note that begins Differs from Stata means the R code does the same job, but a default, the missing-value handling, an estimator or the output layout differs; the note says how. Other notes are practical tips. Most R snippets are run against controlled checks when the catalogue is built; this tests the R code itself, not numerical agreement with Stata. Missing-value comparisons, weights, factor reference levels, join rules and standard-error corrections need particular care. Known gaps are explained explicitly, and related search results are not a translation of unsupported syntax.

In the tables below, data is your dataset, data1 and data2 are the master and using data of a merge, and fit is a fitted model. Most entries use dplyr, so attach it with library(dplyr) or library(tidyverse).

Alphabetical command index

F · Fden · Ftail · about · ac · ado · adopath · alpha · ameans · anova · append · arch · areg · arfima · arfimasoc · args · arima · arimasoc · assert · assertnested · avplots · bayesboot · bayesmh · bayespredict · bayesreps · bayesstats · bayestest · betaden · betareg · binomial · binomialp · binomialtail · binormal · binreg · binscatter · biprobit · bitest · bitesti · bootstrap · boottest · boxcox · brier · browse · bsample · bsqreg · bstat · ca · camat · candisc · canon · capture · carryforward · cauchy · cauchyden · cauchytail · cc · cci · cd · ceil · cem · centile · cf · changeeol · char · checksum · chi2 · chi2den · chi2tail · ci · cii · ciwidth · clear · clock · cloglog · clonevar · cls · cluster · clustermat · cnsreg · codebook · coefplot · cofd · collapse · compare · compress · cond · confirm · constraint · continue · contract · contrast · copy · corr2data · correlate · corrgram · count · cpoisson · creturn · cross · cs · csdid · csi · cumsp · cumul · d. · dataex · datasignature · date · day · daysinmonth · decode · describe · destring · dfbeta · dfgls · dfuller · did_imputation · didregress · dir · discrim · display · distinct · do · dofc · dofm · dofq · dofy · dotplot · dow · doy · drawnorm · drdid · drop · ds · dstdize · dtable · duplicates · ebalance · egen · eivreg · elasticnet · encode · ereturn · error · esize · esizei · estat · estimates · eststo · esttab · etable · eventstudyinteract · exit · expand · expandcl · exponential · exponentialden · exponentialtail · export · f. · factor · factormat · fcast · fcollapse · file · filefilter · fillin · findfile · findit · firstdayofmonth · flevelsof · floor · fmerge · foreach · forecast · format · forvalues · fracreg · fralias · frame · fre · frget · frlink · frunalias · ftools · gammaden · gammap · gammaptail · gcollapse · gcontract · gdistinct · gduplicates · gegen · gencohort · generate · getmata · gettoken · gisid · glevelsof · glm · global · gquantiles · graph · greshape · gsort · gstats · gtoplevelsof · gunique · halfyear · hashsort · hausman · heatplot · heckman · help · hetregress · hexdump · hh · histogram · hotelling · hypergeometric · hypergeometricp · ibeta · ibetatail · icc · if · import · include · infile · infix · inlist · input · inrange · insobs · inspect · intreg · invF · invFtail · invbinomial · invbinomialtail · invcauchy · invcauchytail · invchi2 · invchi2tail · invexponential · invexponentialtail · invgammap · invgammaptail · invibeta · invibetatail · invlogistic · invlogistictail · invnF · invnFtail · invnbinomial · invnbinomialtail · invnchi2 · invnchi2tail · invnibeta · invnormal · invnt · invnttail · invpoisson · invpoissontail · invt · invttail · invtukeyprob · invweibull · invweibullph · invweibullphtail · invweibulltail · ipolate · iqreg · ir · irf · iri · isid · istdize · ivlpirf · ivreg2 · ivreghdfe · ivregress · jackknife · jdbc · joinby · kap · kdensity · keep · kmatch · ksmirnov · ktau · kwallis · l. · label · labelbook · labmask · lasso · levelsof · lincom · line · linktest · list · ln · lncauchyden · lnigammaden · lnmvnormalden · lnnormal · lnnormalden · local · log · logistic · logisticden · logistictail · logit · lookfor · lower · lowess · lpirf · lrtest · ltable · macro · manova · manovatest · margins · marginsplot · mark · markin · markout · marksample · matlist · matname · matrix · mca · mcc · mcci · mdesc · mds · mdsmat · mdy · mean · mecloglog · median · meglm · melogit · memory · menbreg · menl · meologit · meoprobit · mepoisson · meprobit · merge · meta · mhodds · mi · missing · missings · misstable · mixed · mkdir · mkmat · mlexp · mlogit · mm · mofd · month · mvdecode · mvencode · mvreg · mvtest · nF · nFden · nFtail · nbetaden · nbinomial · nbinomialp · nbinomialtail · nbreg · nchi2 · nchi2den · nchi2tail · nestreg · net · newey · nibeta · nl · nlcom · normal · normalden · notes · npnF · npnchi2 · npnt · nptrend · nt · nttail · numlabel · numlist · oaxaca · odbc · ologit · oneway · oprobit · order · orthog · orthpoly · outfile · outreg2 · pac · pca · pcamat · pchi · pcorr · pctile · pergram · permute · pnorm · poisson · poissonp · poissontail · post · postclose · postfile · power · pperron · ppmlhdfe · predict · predictnl · preserve · probit · program · proportion · prtest · prtesti · psdensity · psmatch2 · pstest · putdocx · putexcel · putmata · pwcompare · pwcorr · pwd · pwmean · qchi · qnorm · qofd · qqplot · qreg · quadchk · quantile · quarter · query · quietly · range · rangestat · ranksum · rbeta · rbinomial · rcauchy · rchi2 · rdbwdensity · rdbwselect · rddensity · rdrobust · real · recast · recode · regexm · regexr · regexreplaceall · regexs · reghdfe · regress · rename · replace · require · reshape · return · rexponential · rgamma · rhypergeometric · rlogistic · rnbinomial · rnormal · robvar · roccomp · roctab · rolling · rotate · rotatemat · round · rpoisson · rreg · rt · runiform · runtest · rvfplot · rweibull · sample · save · saveold · savespss · scalar · scatter · sdtest · sdtesti · search · sem · separate · seqvar · serrbar · set · setroot · signrank · signtest · simulate · sktest · sleep · slogit · snapshot · snapspan · sort · spbalance · spdistance · spearman · spgenerate · spikeplot · split · splitsample · spmatrix · spset · sqreg · ss · ssc · sspace · stack · stbase · stci · stcox · stcrreg · stdescribe · stem · stfill · stgen · stintreg · stir · stjoin · stmh · stptime · strate · streg · string · stritrim · strlen · strlower · strltrim · strmatch · strofreal · strpos · strproper · strreverse · strrtrim · strtoname · strtrim · strupper · sts · stset · stsplit · stsum · sttocc · stvary · subinstr · subinword · substr · sum · summarize · svmat · svy · svydescribe · svyset · swilk · symmetry · symmi · symplot · syntax · synth · sysdir · sysuse · t · tab1 · tab2 · tabdisp · tabi · table · tabodds · tabstat · tabulate · tden · tebalance · teffects · tempfile · tempname · tempvar · teoverlap · test · testnl · testparm · tetrachoric · timer · tnbreg · tobit · tokenize · tostring · tpoisson · truncreg · tsfill · tsfilter · tsline · tsreport · tsset · tssmooth · ttail · ttest · ttesti · tukeyprob · twoway · type · uchar · ucm · unab · unabcmd · unicode · univar · unzipfile · upper · use · uselabel · ustrlen · ustrlower · ustrnormalize · ustrpos · ustrregexm · ustrregexra · ustrregexrf · ustrreverse · ustrtrim · ustrupper · usubstr · var · vargranger · varstable · vec · vecrank · version · viewsource · vif · vioplot · webuse · weibull · weibullden · weibullph · weibullphden · weibullphtail · weibulltail · which · while · winsor2 · wntestq · word · wordcount · xcorr · xi · xpose · xtabond · xtcloglog · xtdescribe · xtdidregress · xtdpd · xtdpdsys · xtgee · xtgls · xthtaylor · xtile · xtivreg · xtline · xtlogit · xtologit · xtoprobit · xtpcse · xtpoisson · xtprobit · xtrc · xtreg · xtregar · xtscc · xtset · xtsum · xttest0 · xtunitroot · year · ym · yq · zinb · zip · zipfile · ztest · ztesti

Basics

Stata R Purpose, qualifications and sources
cd "path/to/folder"
setwd("path/to/folder")
base
Change the working directory
An RStudio project sets the working directory for you, so scripts can use relative paths.
Stata reference · R reference
clear
rm(data)
base
Remove a dataset from memory
Rarely needed: R holds many tables at once, each under its own name.
Stata reference · R reference
dir
dir()
base
List the files in the working directory
Stata reference · R reference
display 2 + 2
2 + 2
base
Calculate and show a result
Stata reference · R reference
do analysis.do
source("analysis.R")
base
Run a script file
Stata reference · R reference
export delimited data.csv
readr::write_csv(data, "data.csv")
readr
Export a CSV file
Stata reference · R reference
export excel data.xlsx
writexl::write_xlsx(data, "data.xlsx")
writexl
Export an Excel file
Stata reference · R reference
findit command
findit(command)
tidystata
Find the R equivalent of a Stata command
Bare words and comma-separated names work: findit(tab, sex, region). Add hints such as findit(tab, gen), or quote full Stata syntax. One clear example is shown by default; print(n = Inf) reveals every match. findit() with no argument returns the whole list.
Stata reference · R reference
global path "path/to/folder"
path <- "path/to/folder"
base
Store a value for later use
Any R object works like a macro: assign it once and reuse its name, as in setwd(path).
Stata reference · R reference
help command
help(function_name)
utils
Open the help page of a function
?function does the same. In RStudio you can also search the Help pane.
Stata reference · R reference
import delimited data.csv
data <- readr::read_csv("data.csv")
readr
Import a CSV file
RStudio's File > Import Dataset menu writes this code for you.
Stata reference · R reference
import excel data.xlsx, firstrow
data <- readxl::read_excel("data.xlsx")
readxl
Import an Excel sheet
Stata reference · R reference
import sas data.sas7bdat
data <- haven::read_sas("data.sas7bdat")
haven
Import a SAS file
Stata reference · R reference
import spss data.sav
data <- haven::read_sav("data.sav")
haven
Import an SPSS file
Stata reference · R reference
log using results.log
sink("results.log")
base
Record console output in a file
Most R users write an R Markdown or Quarto report instead of a log.
Stata reference · R reference
net install package, from(url)
remotes::install_github("user/package")
remotes
Install a package from GitHub
Stata reference · R reference
pwd
getwd()
base
Show the working directory
Stata reference · R reference
save data.dta, replace
haven::write_dta(data, "data.dta")
haven
Save as a Stata dataset
saveRDS(data, "data.rds") keeps every R type, such as factors and dates, exactly.
Stata reference · R reference
saveold data.dta, version(13)
haven::write_dta(data, "data.dta", version = 13)
haven
Save for an older Stata version
Stata reference · R reference
search keyword
help.search("keyword")
utils
Search all installed help pages
??keyword is a shortcut. To find the R version of a Stata command, use findit().
Stata reference · R reference
ssc install package
install.packages("package")
utils
Install a package
Unlike Stata, an installed package must be attached in every session with library(package).
Stata reference · R reference
sysuse auto
data("mtcars")
datasets
Load an example dataset
Stata reference · R reference
use data.dta
data <- haven::read_dta("data.dta")
haven
Open a Stata dataset
Variable and value labels are kept. Data saved in R's own format open with readRDS("data.rds") or load("data.RData").
Stata reference · R reference
webuse nlswork
data <- haven::read_dta("https://www.stata-press.com/data/r18/nlswork.dta")
haven
Load an example dataset from the Stata website
Stata reference · R reference

Explore data

Stata R Purpose, qualifications and sources
anova y group
summary(aov(y ~ factor(group), data = data))
stats
Analysis of variance
Stata reference · R reference
browse
browse(data)
tidystata
View the data in a spreadsheet window
Stata reference · R reference
browse x1 x3-x5
browse(data, x1, x3:x5)
tidystata
View selected variables
Ranges of variables use a colon (x3:x5), not a dash.
Stata reference · R reference
browse *x
select(data, ends_with("x"))
dplyr
Variables whose names end with given text
Stata reference · R reference
browse *x*
select(data, contains("x"))
dplyr
Variables whose names contain given text
Stata reference · R reference
browse if x1 == 1 & x2 == 2
filter(data, x1 == 1 & x2 == 2)
dplyr
Rows meeting a condition
Stata reference · R reference
browse in -10/-1
tail(data, 10)
base
The last rows
Stata reference · R reference
browse in 1/10
head(data, 10)
base
The first rows
Stata reference · R reference
browse in 7/12
slice(data, 7:12)
dplyr
Rows by position
Stata reference · R reference
browse x*
select(data, starts_with("x"))
dplyr
Variables whose names start with given text
Stata reference · R reference
browse x* y*
browse(data, varlist("x* y*"))
tidystata
View variables matching Stata wildcards
varlist() understands Stata's * and ? wildcards and works in any selection, such as select().
Stata reference · R reference
ci mean x
t.test(data$x)$conf.int
stats
Confidence interval of a mean
Add conf.level = 0.99 for ci mean x, level(99).
Stata reference · R reference
codebook
codebook(data)
tidystata
Describe every variable
Stata reference · R reference
codebook, compact
summ(data)
tidystata
One line of statistics per variable
Stata reference · R reference
correlate x1 x2 x3
corr(data, x1, x2, x3)
tidystata
Pearson correlations (complete cases)
Differs from Stata: Uses one common complete-case sample, like Stata correlate. Returns r and n in a tidy table; .wide = TRUE gives a lower-triangular table. Stata covariance, means and display-formatting options are not implemented.
Stata reference · R reference
describe
variables(data)
tidystata
List variables with their types and labels
glimpse(data) gives a compact view with the first values of each variable.
Stata reference · R reference
describe using data.dta
haven::read_dta("data.dta", n_max = 0)
haven
Variables in a file, without loading its data
Stata reference · R reference
ds
ds(data)
tidystata
List variable names
ds(data, .type = "table") returns the names as a one-column table; names(data) is base R.
Stata reference · R reference
dtable x1 x2, by(group)
gtsummary::tbl_summary(data, by = group, include = c(x1, x2))
gtsummary
Descriptive Table 1 (Stata 18+)
modelsummary::datasummary_skim(data) gives a quick overview without a by variable.
Stata reference · R reference
factor x1 x2 x3
factanal(na.omit(select(data, x1, x2, x3)), factors = 1)
stats
Factor analysis
Differs from Stata: factanal() uses maximum likelihood; psych::fa(..., fm = "pa") gives Stata's default principal-factor method.
Stata reference · R reference
fre x
fre(data, x)
tidystata
Frequency table with totals
Like Ben Jann's fre: tab() with a total row.
Stata reference · R reference
inspect x
summ(data, x, .detail = TRUE)
tidystata
Distribution, zeros and missing values of a variable
hist(data$x) adds the quick histogram that inspect draws.
Stata reference · R reference
ksmirnov x, by(group)
ks.test(data$x[data$group == 0], data$x[data$group == 1])
stats
Kolmogorov-Smirnov test of equal distributions
Differs from Stata: The R code assumes group codes 0 and 1; exact/asymptotic inference and tied-value handling can differ from Stata ksmirnov.
Stata reference · R reference
ktau x y
cor.test(data$x, data$y, method = "kendall")
stats
Kendall's tau
Differs from Stata: The rank coefficient has the same interpretation, but exact/asymptotic p-value selection and tie corrections may differ; match inference options separately.
Stata reference · R reference
kwallis x, by(group)
kruskal.test(x ~ group, data = data)
stats
Kruskal-Wallis test
Stata reference · R reference
levelsof x
sort(unique(data$x))
base
Distinct values of a variable
Differs from Stata: Store them for a loop: levels <- sort(unique(data$x)), then for (v in levels) { ... }. sort(unique()) excludes NA by default, but string ordering follows R collation and can differ from Stata sorting.
Stata reference · R reference
list
print_all(data)
tidystata
Print the first and last rows
Prints every row and column. Typing data prints the first rows; print_headtail(data) prints the first and last rows.
Stata reference · R reference
list x
pull(data, x)
dplyr
Print one variable
data$x does the same. select(data, x) keeps x as a one-column table.
Stata reference · R reference
lookfor income
variables_search(data, "income")
tidystata
Find variables by name or label
Stata reference · R reference
mean x
summ(data, x, .stat = c("mean", "se"))
tidystata
Mean with its standard error
Differs from Stata: t.test(data$x) also reports the confidence interval. The R snippet returns point summaries only (plus SE for mean); Stata also reports confidence intervals and estimation results.
Stata reference · R reference
oneway y group
summary(aov(y ~ factor(group), data = data))
stats
One-way analysis of variance
Differs from Stata: bartlett.test(y ~ group, data = data) gives the equal-variance test that oneway reports. aov() gives the ANOVA table but does not include the Bartlett equal-variance test printed by oneway; request bartlett.test() separately.
Stata reference · R reference
pca x1 x2 x3
prcomp(na.omit(select(data, x1, x2, x3)), scale. = TRUE)
stats
Principal components
Differs from Stata: Stata analyses the correlation matrix, so scale. = TRUE matches it. scale. = TRUE matches correlation PCA; signs of eigenvectors are arbitrary and the stored rotations and printed loadings have different normalization conventions.
Stata reference · R reference
proportion x
prop.table(table(data$x))
base
Proportion in each category
Differs from Stata: tab(data, x) shows the same percentages; prop.test() adds a confidence interval for one proportion. The R snippet returns point summaries only (plus SE for mean); Stata also reports confidence intervals and estimation results.
Stata reference · R reference
prtest x == 0.5
prop.test(sum(data$x == 1, na.rm = TRUE), sum(!is.na(data$x)), p = 0.5, correct = FALSE)
stats
Test of a proportion
Differs from Stata: correct = FALSE gives Stata's normal-approximation test without continuity correction. The uncorrected test statistic matches the normal approximation, but prop.test() confidence intervals use score inversion rather than the prtest Wald interval.
Stata reference · R reference
pwcorr x1 x2 x3
pwcorr(data, x1, x2, x3)
tidystata
Pairwise correlations
Differs from Stata: Gives r, n and p for each pair; .wide = TRUE gives the matrix. Base R: cor(select(data, x1, x2, x3), use = "pairwise.complete.obs"). pwcorr() returns pair counts and p-values in a tidy table; Stata prints a correlation matrix by default and needs options for additional reporting.
Stata reference · R reference
ranksum x, by(group)
wilcox.test(x ~ group, data = data)
stats
Wilcoxon rank-sum (Mann-Whitney) test
Differs from Stata: R can choose exact inference in small samples and applies continuity correction in its normal approximation; Stata defaults differ. Set exact and correct deliberately.
Stata reference · R reference
signrank x = y
wilcox.test(data$x, data$y, paired = TRUE)
stats
Wilcoxon signed-rank test
Differs from Stata: R can choose exact inference in small samples and applies continuity correction in its normal approximation; Stata defaults differ. Set exact and correct deliberately.
Stata reference · R reference
sktest x
summ(data, x, .stat = c("skew", "kurtosis"))
tidystata
Skewness and kurtosis
For a formal normality test use shapiro.test(data$x).
Stata reference · R reference
spearman x y
cor.test(data$x, data$y, method = "spearman")
stats
Spearman rank correlation
Differs from Stata: The rank coefficient has the same interpretation, but exact/asymptotic p-value selection and tie corrections may differ; match inference options separately.
Stata reference · R reference
stem x
stem(data$x)
graphics
Stem-and-leaf display
Stata reference · R reference
summarize
summ(data)
tidystata
Summary statistics for all variables
Differs from Stata: summary(data) is the base R version, with a less tidy layout. summ() also reports missing counts and has its own default statistic layout; select .stat explicitly when matching Stata output.
Stata reference · R reference
summarize x
summ(data, x)
tidystata
Summary statistics for one variable
Differs from Stata: summ() also reports missing counts and has its own default statistic layout; select .stat explicitly when matching Stata output.
Stata reference · R reference
bysort group: summarize x
summ(data, x, .by = group)
tidystata
Summary statistics by group
Differs from Stata: group_by(data, group) |> summ(x) gives the same result. summ() also reports missing counts and has its own default statistic layout; select .stat explicitly when matching Stata output.
Stata reference · R reference
summarize x [aweight = w]
summ(data, x, .wt = w, .wt_type = "analytic")
tidystata
Weighted summary statistics
Differs from Stata: Frequency weights are the default: summ(data, x, .wt = w). summ() also reports missing counts and has its own default statistic layout; select .stat explicitly when matching Stata output.
Stata reference · R reference
summarize x, detail
summ(data, x, .detail = TRUE)
tidystata
Detailed statistics, including percentiles
Differs from Stata: Pick single statistics with .stat, as in summ(data, x, .stat = "p25"). summ() also reports missing counts and has its own default statistic layout; select .stat explicitly when matching Stata output.
Stata reference · R reference
swilk x
shapiro.test(data$x)
stats
Shapiro-Wilk normality test
Differs from Stata: shapiro.test() accepts 3 to 5000 nonmissing observations; Stata swilk has different sample-size limits and reporting.
Stata reference · R reference
tab1 x1 x2 x3
tab1(data, x1, x2, x3)
tidystata
One frequency table per variable
Differs from Stata: tidystata retains missing categories by default; Stata tabulate excludes them unless missing is specified. Use .missing = FALSE to match Stata.
Stata reference · R reference
tab2 x1 x2
tab2(data, x1, x2)
tidystata
Cross-tabulation of two variables
Differs from Stata: With three or more variables, tab2(data, x1, x2, x3) returns every pairwise table, as Stata does. tidystata retains missing categories by default; Stata tabulate excludes them unless missing is specified. Use .missing = FALSE to match Stata.
Stata reference · R reference
table x1 x2 x3
tab(data, x1, x2, x3)
tidystata
Joint frequencies of several variables
Stata reference · R reference
table x, statistic(mean y)
summ(data, y, .by = x, .stat = "mean")
tidystata
A statistic by category (Stata 17+ table)
Stata reference · R reference
tabstat x1 x2, by(group) stat(mean sd)
tabstat(data, x1, x2, .by = group, .stat = c("mean", "sd"))
tidystata
Chosen statistics by group
Differs from Stata: R retains missing grouping keys; Stata tabstat by() and tabulate summarize() exclude missing grouping categories unless requested. Check the intended grouping sample.
Stata reference · R reference
tabulate x
tab(data, x)
tidystata
One-way frequency table
Differs from Stata: tidystata retains missing categories by default; Stata tabulate excludes them unless missing is specified. Use .missing = FALSE to match Stata.
Stata reference · R reference
tabulate x1 x2
tab2(data, x1, x2)
tidystata
Two-way cross-tabulation
Differs from Stata: fre2(data, x1, x2) adds row and column totals. tidystata retains missing categories by default; Stata tabulate excludes them unless missing is specified. Use .missing = FALSE to match Stata.
Stata reference · R reference
bysort g: tabulate x
tab(data, x, .by = g)
tidystata
Frequency table by group
Differs from Stata: tidystata retains missing categories by default; Stata tabulate excludes them unless missing is specified. Use .missing = FALSE to match Stata.
Stata reference · R reference
tabulate x [aweight = w]
tab(data, x, .wt = w, .wt_type = "analytic")
tidystata
Frequencies with analytic (sampling) weights
Differs from Stata: tidystata retains missing categories by default; Stata tabulate excludes them unless missing is specified. Use .missing = FALSE to match Stata.
Stata reference · R reference
tabulate x [fweight = n]
tab(data, x, .wt = n)
tidystata
Frequencies with frequency weights
Differs from Stata: tidystata retains missing categories by default; Stata tabulate excludes them unless missing is specified. Use .missing = FALSE to match Stata.
Stata reference · R reference
tabulate x, missing
tab(data, x)
tidystata
Frequencies including missing values
tab() always lists missing values as a separate row.
Stata reference · R reference
tabulate x, summarize(y)
summ(data, y, .by = x)
tidystata
Summary of y within each category of x
Differs from Stata: R retains missing grouping keys; Stata tabstat by() and tabulate summarize() exclude missing grouping categories unless requested. Check the intended grouping sample.
Stata reference · R reference
tabulate x1 x2, chi2
tab2(dplyr::filter(data, !is.na(x1), !is.na(x2)), x1, x2, .chi2 = TRUE)
tidystata
Chi-square test of independence
Differs from Stata: Filter missing values on both variables for plain Stata tabulate, chi2. tab2 otherwise includes its displayed missing categories in the Pearson test. tidystata retains missing categories by default; Stata tabulate excludes them unless missing is specified. Use .missing = FALSE to match Stata.
Stata reference · R reference
tabulate x1 x2, exact
fisher.test(data$x1, data$x2)
stats
Fisher's exact test
Stata reference · R reference
ttest x, by(group)
t.test(x ~ group, data = data)
stats
Two-sample t test
Differs from Stata: R's default is Welch's test; add var.equal = TRUE for Stata's default equal-variance test.
Stata reference · R reference
univar x1 x2
summ(data, x1, x2, .detail = TRUE)
tidystata
Detailed univariate statistics
Stata reference · R reference

Check data

Stata R Purpose, qualifications and sources
assert x > 0
assert(data, x > 0)
tidystata
Stop when a condition fails
Differs from Stata: Reports the number of contradictions and returns the data, so it fits in a pipe. Missing x counts as a contradiction, unlike Stata, where missing is larger than any number: write assert(data, is.na(x) | x > 0) for Stata's behaviour.
Stata reference · R reference
confirm variable x
stopifnot("x" %in% names(data))
base
Check that a variable exists
Stata reference · R reference
count
nrow(data)
base
Number of rows
Stata reference · R reference
count if x > 0
sum(data$x > 0, na.rm = TRUE)
base
Count rows meeting a condition
Differs from Stata: Stata numeric missing values compare larger than every finite number; R comparisons return NA. Handle missing values explicitly before applying the condition.
Stata reference · R reference
distinct x1 x2, joint
nrow(distinct(data, x1, x2))
dplyr
Number of distinct combinations
Stata reference · R reference
duplicates list x1 x2
duplicates_list(data, x1, x2)
tidystata
List duplicated rows
Stata reference · R reference
duplicates report x1 x2
duplicates_report(data, x1, x2)
tidystata
Count duplicated rows
Stata reference · R reference
duplicates tag x1 x2, generate(dup)
duplicates_tag(data, x1, x2, .name = "dup")
tidystata
Mark duplicated rows
Stata reference · R reference
isid id wave
isid(data, id, wave)
tidystata
Check that variables identify the rows
Stata reference · R reference
mdesc
summ(data, .stat = "missing")
tidystata
Missing values per variable
Stata reference · R reference
misstable patterns
misstable(data, .patterns = TRUE)
tidystata
Missing-value patterns
1 marks an observed value and 0 a missing one, as in Stata.
Stata reference · R reference
misstable summarize
misstable(data)
tidystata
Missing values per variable
Base R: colSums(is.na(data)).
Stata reference · R reference

Labels

Stata R Purpose, qualifications and sources
decode x, generate(str_x)
mutate(data, str_x = decode(x))
tidystata
Turn labelled values into text
Stata reference · R reference
encode str_x, generate(x)
mutate(data, x = factor(str_x))
dplyr
Turn text into labelled categories
Differs from Stata: factor() creates integer level indices with an R class; encode creates numeric codes with a separate value-label definition. Collation can change code ordering.
Stata reference · R reference
label define gender 1 "male" 2 "female"
mutate(data, gender = factor(gender, levels = 1:2, labels = c("male", "female")))
dplyr
Label every value of a categorical variable
In R a labelled categorical variable is usually a factor. Give levels explicitly so each code gets the right label.
Stata reference · R reference
label drop yesno
mutate(data, x = haven::zap_labels(x))
haven
Remove value labels
Stata reference · R reference
label list x
levels(data$x)
base
Show the categories of a variable
For labelled data read with haven, use haven::print_labels(data$x).
Stata reference · R reference
label values x yesno
mutate(data, x = haven::labelled(x, yesno))
haven
Attach a value label to a variable
Define the labels once, as yesno <- c(No = 0, Yes = 1), then attach them to any variable; factor() is the usual R alternative.
Stata reference · R reference
label variable x "Variable name"
labelled::set_variable_labels(data, x = "Variable name")
labelled
Label a variable
Labels read from Stata files are kept; variables() and codebook() display them.
Stata reference · R reference
label define x 9 "Unknown" 10 "Refused"
mutate(data, x = haven::labelled(x, c(Unknown = 9, Refused = 10)))
haven
Label some values only
Partial value labels are rare in R; haven keeps them so they survive a round trip to Stata. tab() and codebook() show them.
Stata reference · R reference
notes x: Collected in wave 2
attr(data$x, "note") <- "Collected in wave 2"
base
Attach a note to a variable
R has no notes system; an attribute or a comment in the script is the usual substitute.
Stata reference · R reference

Construct and modify variables

Stata R Purpose, qualifications and sources
generate y = ceil(x)
mutate(data, y = ceiling(x))
base
Round up
Stata reference · R reference
clonevar x2 = x
mutate(data, x2 = x)
dplyr
Copy a variable
Differs from Stata: mutate(x2 = x) copies the R vector and attributes, but does not reproduce all Stata clonevar characteristics and notes.
Stata reference · R reference
collapse (mean) x1 x2, by(group)
summarise(data, across(c(x1, x2), ~ mean(.x, na.rm = TRUE)), .by = group)
dplyr
Replace the data with group means
Differs from Stata: Assign the result to replace the data, as collapse does: data <- summarise(...). summ(data, x1, x2, .by = group) shows a summary table instead. R retains missing grouping keys; Stata tabstat by() and tabulate summarize() exclude missing grouping categories unless requested. Check the intended grouping sample.
Stata reference · R reference
collapse (count) n = x (sum) total = y, by(group)
summarise(data, n = sum(!is.na(x)), total = sum(y, na.rm = TRUE), .by = group)
dplyr
Different statistics for different variables
Stata reference · R reference
generate y = cond(x > 0, 1, 0)
mutate(data, y = if_else(x > 0, 1, 0))
dplyr
One value if a condition holds, another if not
Differs from Stata: With missing x, Stata's cond() takes the first value (missing counts as large); if_else() returns NA. Stata numeric missing values compare larger than every finite number; R comparisons return NA. Handle missing values explicitly before applying the condition.
Stata reference · R reference
destring str_x, generate(num_x)
mutate(data, num_x = destring(str_x))
tidystata
Text to numbers
Differs from Stata: Text that is not a number becomes NA with a warning, as with force. destring(str_x, ignore = "kg") removes those characters first, like ignore(), so "10 kg" gives 10. Invalid numeric text becomes NA with a warning here; Stata destring without force refuses conversion of a variable containing such text.
Stata reference · R reference
egen bins = cut(x), group(10)
mutate(data, bins = xtile(x, 10))
tidystata
Ten groups of about equal size
Differs from Stata: egen cut(), group() has its own grouping rule; xtile() follows Stata's xtile, the usual command for quantile groups.
Stata reference · R reference
egen first = tag(group)
mutate(data, first = is_first(group))
tidystata
Mark the first row of each group
Differs from Stata: Gives TRUE/FALSE; rows with a missing group are FALSE, as in Stata, unless .missing = TRUE. The R result is logical TRUE/FALSE rather than numeric 1/0; use as.integer() when the stored type matters.
Stata reference · R reference
egen id = group(g1 g2)
data |> group_by(g1, g2) |> mutate(id = cur_group_id()) |> ungroup()
dplyr
Number the groups
Differs from Stata: cur_group_id() also numbers groups with missing keys; egen group() excludes those rows without the missing option. String collation can change ID ordering.
Stata reference · R reference
egen x_avg = mean(x)
mutate(data, x_avg = mean(x, na.rm = TRUE))
dplyr
Sample statistic as a new variable
Differs from Stata: R functions keep missing values unless na.rm = TRUE; Stata's egen ignores them. For an all-missing group mean(..., na.rm = TRUE) gives NaN; Stata egen mean() gives numeric missing. Normalize NaN if that distinction matters.
Stata reference · R reference
egen x_sum = rowtotal(x1-x5)
mutate(data, x_sum = row_sum(x1:x5))
tidystata
Row total
Stata reference · R reference
bysort group: egen med = median(x)
mutate(data, med = median(x, na.rm = TRUE), .by = group)
dplyr
Group median
Stata reference · R reference
bysort group: egen mn = min(x)
dplyr::mutate(data, mn = if (all(is.na(x))) NA_real_ else min(x, na.rm = TRUE), .by = group)
dplyr
Group minimum
Differs from Stata: All-missing groups return NA without evaluating min() on an empty set. All-missing groups produce -Inf/Inf and a warning in R max/min with na.rm = TRUE; Stata egen max()/min() returns missing.
Stata reference · R reference
bysort group: egen mx = max(x)
dplyr::mutate(data, mx = if (all(is.na(x))) NA_real_ else max(x, na.rm = TRUE), .by = group)
dplyr
Group maximum
Differs from Stata: All-missing groups return NA without evaluating max() on an empty set. All-missing groups produce -Inf/Inf and a warning in R max/min with na.rm = TRUE; Stata egen max()/min() returns missing.
Stata reference · R reference
bysort group: egen n = count(x)
mutate(data, n = sum(!is.na(x)), .by = group)
dplyr
Number of observed values in each group
Stata reference · R reference
bysort group: egen s = sd(x)
mutate(data, s = sd(x, na.rm = TRUE), .by = group)
dplyr
Group standard deviation
Stata reference · R reference
bysort group: egen tot = total(x)
mutate(data, tot = sum(x, na.rm = TRUE), .by = group)
dplyr
Group total
Stata reference · R reference
bysort group: egen x_avg = mean(x)
mutate(data, x_avg = mean(x, na.rm = TRUE), .by = group)
dplyr
Group statistic as a new variable
Differs from Stata: For an all-missing group mean(..., na.rm = TRUE) gives NaN; Stata egen mean() gives numeric missing. Normalize NaN if that distinction matters.
Stata reference · R reference
egen bins = cut(x), at(0(10)100)
mutate(data, bins = cut(x, breaks = seq(0, 100, 10), right = FALSE))
base
Groups by given cutpoints
Differs from Stata: right = FALSE makes each interval include its lower cutpoint, as egen cut() does. cut_length(x, 10) instead splits the range into 10 equal widths. cut() returns a factor of interval labels; egen cut() stores numeric lower endpoints even when interval closure matches.
Stata reference · R reference
egen first = rowfirst(x1-x5)
mutate(data, first = coalesce(x1, x2, x3, x4, x5))
dplyr
First observed value across variables
Stata reference · R reference
egen id = concat(a b), punct(_)
mutate(data, id = paste(a, b, sep = "_"))
base
Join variables into one string
Differs from Stata: paste() turns NA into the text "NA"; egen concat() follows Stata missing-value and numeric-display conventions.
Stata reference · R reference
egen last = rowlast(x1-x5)
mutate(data, last = coalesce(x5, x4, x3, x2, x1))
dplyr
Last observed value across variables
Stata reference · R reference
egen n9 = anycount(x1-x5), values(9)
mutate(data, n9 = rowSums(across(x1:x5, ~ .x %in% 9)))
dplyr
Count how many variables equal a value
Stata reference · R reference
egen p = pc(x)
mutate(data, p = pc(x))
tidystata
Percentage of the total
pc(x, prop = TRUE) gives proportions, like the prop option.
Stata reference · R reference
egen r = rank(x)
mutate(data, r = rank(x, na.last = "keep"))
base
Rank, with ties averaged
rank() gives tied values their average rank, like egen rank(); dplyr::min_rank() gives them the lowest.
Stata reference · R reference
egen s = seq(), from(1) to(3)
mutate(data, s = rep_len(1:3, n()))
dplyr
Repeating sequence
Stata reference · R reference
egen x_avg = rowmean(x1-x5)
mutate(data, x_avg = row_mean(x1:x5))
tidystata
Row mean
Stata reference · R reference
egen x_max = rowmax(x1-x5)
mutate(data, x_max = row_max(x1:x5))
tidystata
Row maximum
Stata reference · R reference
egen x_med = rowmedian(x1-x5)
mutate(data, x_med = row_median(x1:x5))
tidystata
Row median
Stata reference · R reference
egen x_mi = rowmiss(x1-x5)
mutate(data, x_mi = row_miss(x1:x5))
tidystata
Number of missing values in each row
Stata reference · R reference
egen x_min = rowmin(x1-x5)
mutate(data, x_min = row_min(x1:x5))
tidystata
Row minimum
Stata reference · R reference
egen x_n = rownonmiss(x1-x5)
mutate(data, x_n = row_non_miss(x1:x5))
tidystata
Number of observed values in each row
Stata reference · R reference
egen x_nv = rownvals(x1-x5)
mutate(data, x_nv = row_nvals(x1:x5))
tidystata
Number of distinct values in each row
From egenmore (SSC). Missing values are ignored unless .missing = TRUE, like the missing option.
Stata reference · R reference
egen x_sd = rowsd(x1-x5)
mutate(data, x_sd = row_sd(x1:x5))
tidystata
Row standard deviation
Stata reference · R reference
egen z = std(x)
mutate(data, z = std(x))
tidystata
Standardise a variable
Base R: as.vector(scale(x)). Add .by = g for by g: egen.
Stata reference · R reference
generate y = floor(x)
mutate(data, y = floor(x))
base
Round down
Stata reference · R reference
format x %9.2f
mutate(data, x_text = sprintf("%.2f", x))
base
Display numbers with two decimals
R stores the number unchanged and formats it only when printing, for example with round(x, 2) or sprintf().
Stata reference · R reference
generate x2 = x^2
mutate(data, x2 = x^2)
dplyr
Create a variable
Assign the result to keep it: data <- mutate(data, ...). R has no separate generate and replace.
Stata reference · R reference
generate N = _N
mutate(data, N = n())
dplyr
Number of rows
Add .by = group for the number of rows in each group, like bysort group: generate N = _N.
Stata reference · R reference
generate n = _n
mutate(data, n = row_number())
dplyr
Row number
Stata reference · R reference
generate days = d2 - d1
mutate(data, days = as.numeric(d2 - d1))
base
Days between two dates
Stata reference · R reference
generate dummy = (x1 == 1 & x2 == 2)
dplyr::mutate(data, dummy = as.integer(x1 %in% 1 & x2 %in% 2))
dplyr
Dummy variable from a condition
Differs from Stata: Stata numeric equality is false for missing operands; %in% keeps the dummy zero when either input is missing. The R result is logical TRUE/FALSE rather than numeric 1/0; use as.integer() when the stored type matters.
Stata reference · R reference
generate lag_x = x[_n-1]
mutate(data, lag_x = lag(x))
dplyr
Value from the previous row
This shifts rows, like x[_n-1], and ignores gaps in time. See L. for panel lags.
Stata reference · R reference
generate lead_x = x[_n+2]
mutate(data, lead_x = lead(x, 2))
dplyr
Value from two rows ahead
Stata reference · R reference
generate x2 = x^2 if x > 0
mutate(data, x2 = if_else(x > 0, x^2, NA))
dplyr
Create a variable under a condition
In Stata missing is larger than any number, so x > 0 is true for missing x. In R the condition is NA and so is the result.
Stata reference · R reference
generate x2 = x^2 in 11/20
mutate(data, x2 = if_else(row_number() %in% 11:20, x^2, NA))
dplyr
Create a variable for some rows
Stata reference · R reference
generate y = inlist(x, 1, 3, 5)
mutate(data, y = x %in% c(1, 3, 5))
base
Whether x equals any listed value
Differs from Stata: %in% gives FALSE for missing x, as inlist() does. R returns a logical indicator rather than the numeric 1/0 stored by Stata generate; use as.integer() if the stored type matters.
Stata reference · R reference
generate y = inrange(x, 1, 5)
mutate(data, y = between(x, 1, 5))
dplyr
Whether x lies within a range
Differs from Stata: between() returns NA for missing x, whereas Stata's inrange() returns 0.
Stata reference · R reference
generate y = ln(x)
mutate(data, y = log(x))
base
Natural logarithm
Differs from Stata: log10() matches Stata's log10(). R's log(0) is -Inf rather than missing. R log(0) gives -Inf and a negative input gives NaN with a warning; Stata ln() gives numeric missing for these invalid inputs.
Stata reference · R reference
generate m = missing(x)
mutate(data, m = is.na(x))
base
Whether a value is missing
Differs from Stata: R returns a logical indicator rather than the numeric 1/0 stored by Stata generate; use as.integer() if the stored type matters.
Stata reference · R reference
mvdecode x, mv(-9)
mutate(data, x = mvdecode(x, -9))
tidystata
Turn missing-value codes into missing
mvdecode(x, c(-8, -9)) handles several codes, like mv(-8 -9).
Stata reference · R reference
mvencode x, mv(-9)
mutate(data, x = mvencode(x, -9))
tidystata
Turn missing values into a code
Stata reference · R reference
pctile p = x, nquantiles(4)
summ(data, x, .stat = c("p25", "median", "p75"))
tidystata
Quantile cutpoints
Differs from Stata: summ() uses Stata's percentile rule. quantile(x, type = 2) is close, but treats some whole positions, such as 100 * 0.3, as fractional. summ() returns percentile values in a summary table; pctile creates a dataset column containing the cutpoints.
Stata reference · R reference
recast double x
mutate(data, x = as.double(x))
base
Change the storage type
R chooses storage automatically, so there is no compress either.
Stata reference · R reference
recode x (1/5 = 1) (6/10 = 2) (11/15 = 3) (else = .), generate(x3g)
mutate(data, x3g = case_when(between(x, 1, 5) ~ 1, between(x, 6, 10) ~ 2, between(x, 11, 15) ~ 3))
dplyr
Recode ranges of values
Values that match no condition become NA, like else = . in Stata.
Stata reference · R reference
recode x (9 = .)
mutate(data, x = na_if(x, 9))
dplyr
Turn one code into missing
Stata reference · R reference
rename x x2
rename(data, x2 = x)
dplyr
Rename a variable
Note the order: new name = old name.
Stata reference · R reference
rename (a b) (c d)
rename(data, c = a, d = b)
dplyr
Rename several variables
Stata reference · R reference
rename * *_old
rename_with(data, ~ paste0(.x, "_old"))
dplyr
Add a suffix to every name
Stata reference · R reference
rename *, lower
rename_with(data, tolower)
dplyr
Make all names lower case
Stata reference · R reference
rename x*, upper
rename_with(data, toupper, starts_with("x"))
dplyr
Upper-case some names
Stata reference · R reference
replace x = x^2
mutate(data, x = x^2)
dplyr
Change a variable
Stata reference · R reference
replace x = x^2 if x > 0
mutate(data, x = if_else(x > 0, x^2, x))
dplyr
Change a variable under a condition
Differs from Stata: Stata numeric missing values compare larger than every finite number; R comparisons return NA. Handle missing values explicitly before applying the condition.
Stata reference · R reference
replace x = x^2 in 11/20
mutate(data, x = if_else(row_number() %in% 11:20, x^2, x))
dplyr
Change a variable for some rows
Stata reference · R reference
generate z = rnormal()
mutate(data, z = rnorm(n()))
stats
Normal random numbers
Differs from Stata: R and Stata use different random-number streams; the same numeric seed does not reproduce the same draws or selected rows.
Stata reference · R reference
generate y = round(x, 0.1)
mutate(data, y = round(x, 1))
base
Round
Differs from Stata: R's second argument is the number of decimals. R rounds halves to even (round(0.5) is 0); Stata rounds them up.
Stata reference · R reference
generate u = runiform()
mutate(data, u = runif(n()))
stats
Uniform random numbers
Differs from Stata: R and Stata use different random-number streams; the same numeric seed does not reproduce the same draws or selected rows.
Stata reference · R reference
generate cs = sum(x)
mutate(data, cs = cumsum(coalesce(x, 0)))
dplyr
Running sum
Stata's sum() function treats missing values as 0, hence coalesce(x, 0).
Stata reference · R reference
tabulate x, generate(x_)
as_dummy(data, x)
tidystata
Dummy variables for every category
Differs from Stata: as_dummy(data, x, .names = "index") numbers the columns x_1, x_2, ... as Stata does. Also: fastDummies::dummy_cols(data, "x"). as_dummy() defaults to value-based column names; .names = "index" gives numbered Stata-style suffixes. Check the missing-category indicator policy too.
Stata reference · R reference
tostring num_x, generate(str_x)
mutate(data, str_x = tostring(num_x))
tidystata
Numbers to text
Differs from Stata: Labelled values keep their codes; decode() gives the value labels instead. Formatting and retained precision can differ from Stata tostring; choose an explicit format when exact text or round-trip precision matters.
Stata reference · R reference
winsor2 x, cuts(1 99)
mutate(data, x_w = datawizard::winsorize(x, threshold = 0.01))
datawizard
Winsorise at the 1st and 99th percentiles
Differs from Stata: datawizard uses R quantile cutpoints while winsor2 uses Stata percentile rules; small samples and ties can therefore yield different caps.
Stata reference · R reference
xtile q = x, nquantiles(4)
mutate(data, q = xtile(x, 4))
tidystata
Quantile groups
xtile() follows Stata's rule, so equal values stay in the same group.
Stata reference · R reference
xtile q = x [aweight = w], nquantiles(4)
mutate(data, q = xtile(x, 4, wt = w))
tidystata
Weighted quantile groups
Stata reference · R reference

Select variables and rows

Stata R Purpose, qualifications and sources
drop if x == 1
filter(data, x != 1 | is.na(x))
dplyr
Drop rows meeting a condition
Stata keeps rows with missing x here; | is.na(x) does the same in R.
Stata reference · R reference
drop in 1/4
slice(data, -(1:4))
dplyr
Drop rows by position
Stata reference · R reference
drop x
select(data, -x)
dplyr
Drop a variable
Stata reference · R reference
drop if missing(x)
filter(data, !is.na(x))
dplyr
Drop rows where x is missing
Stata reference · R reference
drop x1 x3-x5
select(data, -c(x1, x3:x5))
dplyr
Drop several variables
Positions work too: select(data, -c(1, 3:5)).
Stata reference · R reference
duplicates drop
duplicates_drop(data)
tidystata
Drop rows that duplicate an earlier row
Stata reference · R reference
duplicates drop x1 x2, force
duplicates_drop(data, x1, x2, .force = TRUE)
tidystata
Keep the first row for each key
distinct(data, x1, x2, .keep_all = TRUE) is the dplyr version.
Stata reference · R reference
keep if x1 == 1 & x2 == 2
filter(data, x1 == 1 & x2 == 2)
dplyr
Keep rows meeting a condition
filter() drops rows where the condition is NA, so rows with missing values never pass.
Stata reference · R reference
keep in 1/10
head(data, 10)
base
Keep the first rows
Stata reference · R reference
keep x1 x3-x5
select(data, x1, x3:x5)
dplyr
Keep some variables
Numbers select by position: select(data, 1, 3:5). select_or_transmute() also computes new columns.
Stata reference · R reference
keep if !missing(x)
filter(data, !is.na(x))
dplyr
Keep rows where x is observed
Stata reference · R reference
keep if inlist(x, 1, 3, 5)
filter(data, x %in% c(1, 3, 5))
dplyr
Keep rows with listed values
Stata reference · R reference
keep if inrange(x, 5000, 10000)
filter(data, between(x, 5000, 10000))
dplyr
Keep rows within a range
Stata reference · R reference
keep in -10/-1
tail(data, 10)
base
Keep the last rows
Stata reference · R reference
keep in 7/12
slice(data, 7:12)
dplyr
Keep rows by position
Stata reference · R reference
keep x*
select(data, varlist("x*"))
tidystata
Keep variables matching Stata wildcards
Stata reference · R reference
set seed 2024; sample 10
data |> slice_sample(prop = 0.1) |> set_seed(2024)
tidystata
Reproducible random 10% sample
Differs from Stata: R and Stata use different random-number streams; the same numeric seed does not reproduce the same draws or selected rows.
Stata reference · R reference
set seed 2024; sample 1000, count
data |> slice_sample(n = 1000) |> set_seed(2024)
tidystata
Reproducible random sample of 1000 rows
Differs from Stata: set_seed() sets the seed before the sampling step runs, so the pipe stays in one line. R and Stata use different random-number streams; the same numeric seed does not reproduce the same draws or selected rows.
Stata reference · R reference

Sort

Stata R Purpose, qualifications and sources
gsort x1 -x2
arrange(data, x1, desc(x2))
dplyr
Sort ascending and descending
Stata reference · R reference
order x1-x4
relocate(data, x1:x4)
dplyr
Move variables to the front
Stata reference · R reference
order x1-x4, before(x5)
relocate(data, x1:x4, .before = x5)
dplyr
Move variables before another
Stata reference · R reference
sort x1 x2
arrange(data, x1, x2)
dplyr
Sort in ascending order
Stata reference · R reference

Combine data

Stata R Purpose, qualifications and sources
append using data2
bind_rows(data1, data2)
dplyr
Stack two datasets
Differs from Stata: bind_rows() has R type-promotion and attribute rules; .id creates string source identifiers rather than the numeric codes of append, generate().
Stata reference · R reference
append using data2, generate(source)
dplyr::bind_rows(data1, data2, .id = "source") |> dplyr::mutate(source = as.integer(source) - 1L)
dplyr
Stack datasets and record where each row came from
Differs from Stata: Uses numeric source IDs: zero for the master and one for the first using dataset, as Stata append, generate() does. bind_rows() has R type-promotion and attribute rules; .id creates string source identifiers rather than the numeric codes of append, generate().
Stata reference · R reference
cross using data2
cross_join(data1, data2)
dplyr
Every combination of rows from two datasets
Differs from Stata: cross_join() suffixes overlapping column names; Stata cross keeps master values for overlapping names. Rename overlaps first to obtain the same columns.
Stata reference · R reference
joinby id using data2
inner_join(data1, data2, by = "id", relationship = "many-to-many")
dplyr
All pairs of rows within each id
Differs from Stata: dplyr retains overlapping non-key columns with suffixes instead of Stata master values, creates no _merge, and does not enforce a declared 1:1 key constraint.
Stata reference · R reference
merge 1:1 _n using data2
bind_cols(data1, data2)
dplyr
Put two datasets side by side by row position
Differs from Stata: bind_cols() needs matching row counts (or recyclable one-row inputs) and repairs duplicate names; merge 1:1 _n can retain unmatched rows.
Stata reference · R reference
merge 1:1 id using data2
stata_merge(data1, data2, "1:1", by = "id")
tidystata
Merge with a match report
Like Stata, all rows are kept and a .merge column records the match result. full_join(data1, data2, by = "id") merges without the report.
Stata reference · R reference
merge 1:m id using data2
stata_merge(data1, data2, "1:m", by = "id")
tidystata
One-to-many merge with a match report
Stata reference · R reference
merge m:1 id using data2
stata_merge(data1, data2, "m:1", by = "id")
tidystata
Many-to-one merge with a match report
Stata reference · R reference
merge 1:1 id using data2, keep(master match)
left_join(data1, data2, by = "id")
dplyr
Keep all rows of the master data
Differs from Stata: dplyr retains overlapping non-key columns with suffixes instead of Stata master values, creates no _merge, and does not enforce a declared 1:1 key constraint.
Stata reference · R reference
merge 1:1 id using data2, keep(master) keepusing(id) nogenerate
anti_join(data1, data2, by = "id")
dplyr
Keep rows of data1 whose id is not in data2
Differs from Stata: semi_join()/anti_join() select rows by key membership but do not enforce the unique keys required by Stata merge 1:1; validate uniqueness separately.
Stata reference · R reference
merge 1:1 id using data2, keep(match)
inner_join(data1, data2, by = "id")
dplyr
Keep matched rows only
Differs from Stata: dplyr retains overlapping non-key columns with suffixes instead of Stata master values, creates no _merge, and does not enforce a declared 1:1 key constraint.
Stata reference · R reference
merge 1:1 id using data2, keep(match) keepusing(id) nogenerate
semi_join(data1, data2, by = "id")
dplyr
Keep rows of data1 whose id is in data2
Differs from Stata: semi_join()/anti_join() select rows by key membership but do not enforce the unique keys required by Stata merge 1:1; validate uniqueness separately.
Stata reference · R reference
merge 1:1 id using data2, keep(using match)
right_join(data1, data2, by = "id")
dplyr
Keep all rows of the using data
Differs from Stata: dplyr retains overlapping non-key columns with suffixes instead of Stata master values, creates no _merge, and does not enforce a declared 1:1 key constraint.
Stata reference · R reference
merge 1:1 id1 id2 using data2, nogenerate
full_join(data1, data2, by = c("id1", "id2"))
dplyr
Merge on two keys
Differs from Stata: Variables with the same name in both tables get suffixes; choose them with suffix = c("_data1", "_data2"). dplyr retains overlapping non-key columns with suffixes instead of Stata master values, creates no _merge, and does not enforce a declared 1:1 key constraint.
Stata reference · R reference

Reshape

Stata R Purpose, qualifications and sources
reshape long var, i(id) j(year)
tidyr::pivot_longer(data, tidyselect::starts_with("var"), names_to = "year", names_prefix = "var", names_transform = list(year = as.integer), values_to = "var")
tidyr
Wide to long
Differs from Stata: Converts numeric suffixes to integer year values, matching reshape long without string. pivot_longer() returns a text year without names_transform and does not enforce reshape i()/j() uniqueness constraints.
Stata reference · R reference
reshape wide var, i(id) j(year)
pivot_wider(data, names_from = year, values_from = var, names_prefix = "var")
tidyr
Long to wide
Differs from Stata: Duplicate keys can create list-columns in pivot_wider(); Stata reshape wide rejects duplicate i()/j() combinations. Validate keys first.
Stata reference · R reference
reshape long var, i(id) j(year)
stats::reshape(data, direction = "long", varying = list(c("var2000", "var2001")), v.names = "var", timevar = "year", times = c(2000, 2001), idvar = "id")
stats
Reshape repeated measurements to long form with base R
Differs from Stata: Explicitly list the wide columns and time values. This fixed workflow uses var2000 and var2001; adapt those names to your data.
Stata reference · R reference
reshape wide var, i(id) j(year)
stats::reshape(data, direction = "wide", v.names = "var", timevar = "year", idvar = "id", sep = "")
stats
Reshape repeated measurements to wide form with base R
Differs from Stata: Requires one row per id/year combination. R row ordering and attributes differ from Stata; compare keys and values explicitly.
Stata reference · R reference
xpose, clear
tibble::as_tibble(t(data), .name_repair = "unique")
tibble
Transpose the data
Stata reference · R reference

Construct data

Stata R Purpose, qualifications and sources
expand n
uncount(data, n)
tidyr
Repeat each row n times
Differs from Stata: uncount() drops n afterwards; add .remove = FALSE to keep it. uncount() drops the count column by default and zero counts remove rows; Stata expand keeps the count variable and retains observations when the count is below one.
Stata reference · R reference
fillin x1 x2
complete(data, x1, x2)
tidyr
Add rows for every combination of values
Differs from Stata: expand(data, x1, x2) returns only the combinations; expand_grid(x1 = 1:5, x2 = c("a", "b")) builds them from scratch. complete() adds combinations without the _fillin indicator created by Stata fillin; factor levels and missing-key combinations also need explicit decisions.
Stata reference · R reference
input x y
tibble(x = c(1, 2), y = c(3, 4))
tibble
Type in a small dataset
Stata reference · R reference
set obs 100
data <- tibble(id = 1:100)
tibble
Start a dataset with a given number of rows
Stata reference · R reference

Strings and dates

Stata R Purpose, qualifications and sources
generate z = char(code)
data$z <- vapply(data$code,intToUtf8,character(1))
base
Create characters from ASCII codes
Differs from Stata: Restricted to ASCII codes 1–127; extended-byte encodings are not Unicode code points.
Stata reference · R reference
generate t = clock(s, "YMDhms")
mutate(data, t = lubridate::ymd_hms(s))
lubridate
Text to a date-time
Differs from Stata: R uses Date/POSIXct or tsibble calendar classes, not Stata numeric date/time counts from 1960; convert epochs and time zones when exchanging underlying numeric values.
Stata reference · R reference
generate double z = clock(s, "YMDhms")
data$z <- as.POSIXct(data$s,format='%Y-%m-%d %H:%M:%S',tz='UTC')
base
Parse a date-time with an explicit UTC timezone
Differs from Stata: POSIXct is seconds since 1970 with a timezone; Stata clock is milliseconds since 1960 without a timezone.
Stata reference · R reference
generate double z = cofd(d)
data$z <- as.numeric(data$d-as.Date('1960-01-01'))*86400000
base
Convert R dates to Stata midnight millisecond codes
Differs from Stata: Returns ordinary Stata %tc milliseconds since 1960, not a POSIXct object.
Stata reference · R reference
generate d = date(s, "YMD")
mutate(data, d = lubridate::ymd(s))
lubridate
Text to a date
Differs from Stata: R uses Date/POSIXct or tsibble calendar classes, not Stata numeric date/time counts from 1960; convert epochs and time zones when exchanging underlying numeric values.
Stata reference · R reference
generate z = date(s, "DMY")
data$z <- as.Date(data$s,format='%d/%m/%Y')
base
Parse day-month-year date strings
Differs from Stata: R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.
Stata reference · R reference
generate z = date(s, "MDY")
data$z <- as.Date(data$s,format='%m/%d/%Y')
base
Parse month-day-year date strings
Differs from Stata: R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.
Stata reference · R reference
generate z = date(s, "YMD")
data$z <- as.Date(data$s,format='%Y-%m-%d')
base
Parse year-month-day date strings
Differs from Stata: R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.
Stata reference · R reference
generate dd = day(d)
mutate(data, dd = lubridate::day(d))
lubridate
Day of the month
Stata reference · R reference
generate z = day(d)
data$z <- as.integer(format(data$d,'%d'))
base
Extract day-of-month numbers
Differs from Stata: Accepts an R Date column and returns the demonstrated calendar component; raw Stata date codes require conversion first.
Stata reference · R reference
generate z = daysinmonth(d)
data$z <- as.integer(lubridate::days_in_month(data$d))
lubridate
Get the number of days in each calendar month
Differs from Stata: R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.
Stata reference · R reference
display c(current_date)
Sys.Date()
base
Today's date
Stata reference · R reference
generate z = dofc(milliseconds)
data$z <- as.Date(as.POSIXct(data$milliseconds/1000,origin='1960-01-01',tz='UTC'),tz='UTC')
base
Convert Stata millisecond datetimes to dates
Differs from Stata: For ordinary Stata %tc values without leap-second encoding; UTC supplies a deterministic timezone.
Stata reference · R reference
generate d = dofm(m)
mutate(data, d = as.Date(m))
tsibble
First day of a monthly period
Differs from Stata: Here m is a tsibble::yearmonth() value. R uses Date/POSIXct or tsibble calendar classes, not Stata numeric date/time counts from 1960; convert epochs and time zones when exchanging underlying numeric values.
Stata reference · R reference
generate z = dofm(m)
data$z <- as.Date(sprintf('%04d-%02d-01',1960L+data$m%/%12L,data$m%%12L+1L))
base
Convert Stata monthly codes to month-start dates
Differs from Stata: R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.
Stata reference · R reference
generate z = dofq(q)
data$z <- as.Date(sprintf('%04d-%02d-01',1960L+data$q%/%4L,(data$q%%4L)*3L+1L))
base
Convert Stata quarterly codes to quarter-start dates
Differs from Stata: R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.
Stata reference · R reference
generate z = dofy(year)
data$z <- as.Date(sprintf('%04d-01-01',data$year))
base
Construct the first day of each year
Differs from Stata: R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.
Stata reference · R reference
generate w = dow(d)
mutate(data, w = lubridate::wday(d) - 1)
lubridate
Day of the week
wday() counts Sunday as 1; Stata's dow() counts Sunday as 0.
Stata reference · R reference
generate z = dow(d)
data$z <- as.integer(format(data$d,'%w'))
base
Extract weekday with Sunday coded zero
Differs from Stata: Accepts an R Date column and returns the demonstrated calendar component; raw Stata date codes require conversion first.
Stata reference · R reference
generate z = doy(d)
data$z <- as.integer(format(data$d,'%j'))
base
Extract day-of-year numbers
Differs from Stata: Accepts an R Date column and returns the demonstrated calendar component; raw Stata date codes require conversion first.
Stata reference · R reference
generate z = firstdayofmonth(d)
data$z <- as.Date(format(data$d,'%Y-%m-01'))
base
Find the first date of each calendar month
Differs from Stata: R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.
Stata reference · R reference
format d %td
format(data$d, "%d%b%Y")
base
Display a date
Dates keep their class; format() only changes how they print.
Stata reference · R reference
generate age = (d2 - d1) / 365.25
mutate(data, age = lubridate::time_length(lubridate::interval(d1, d2), "years"))
lubridate
Age or duration in years
Differs from Stata: time_length(interval(...), "years") uses calendar-year lengths; dividing days by 365.25 is a fixed-length approximation and can give different ages.
Stata reference · R reference
generate z = halfyear(d)
data$z <- (as.integer(format(data$d,'%m'))-1L)%/%6L+1L
base
Extract half-year numbers
Differs from Stata: Accepts an R Date column and returns the demonstrated calendar component; raw Stata date codes require conversion first.
Stata reference · R reference
generate z = hh(t)
data$z <- as.integer(format(data$t,'%H',tz='UTC'))
base
Extract the hour from a UTC timestamp
Differs from Stata: Input is an R POSIXct timestamp; convert raw Stata %tc numbers before extracting components.
Stata reference · R reference
generate s = lower(name)
mutate(data, s = str_to_lower(name))
stringr
Lower case
Differs from Stata: R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate d = mdy(m, d, y)
mutate(data, d = lubridate::make_date(y, m, d))
lubridate
Date from year, month and day
Differs from Stata: R uses Date/POSIXct or tsibble calendar classes, not Stata numeric date/time counts from 1960; convert epochs and time zones when exchanging underlying numeric values.
Stata reference · R reference
generate z = mdy(month, day, year)
data$z <- as.Date(sprintf('%04d-%02d-%02d',data$year,data$month,data$day))
base
Construct a date from year, month and day columns
Differs from Stata: R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.
Stata reference · R reference
generate z = mm(t)
data$z <- as.integer(format(data$t,'%M',tz='UTC'))
base
Extract the minute from a UTC timestamp
Differs from Stata: Input is an R POSIXct timestamp; uppercase %M means minute and lowercase %m means month.
Stata reference · R reference
generate m = mofd(d)
mutate(data, m = tsibble::yearmonth(d))
tsibble
Monthly period from a date
Differs from Stata: tsibble::yearquarter() is the quarterly version, like qofd(). R uses Date/POSIXct or tsibble calendar classes, not Stata numeric date/time counts from 1960; convert epochs and time zones when exchanging underlying numeric values.
Stata reference · R reference
generate z = mofd(d)
data$z <- (as.integer(format(data$d,'%Y'))-1960L)*12L+as.integer(format(data$d,'%m'))-1L
base
Convert Date values to Stata monthly codes
Differs from Stata: Returns numeric months since January 1960, explicitly using Stata monthly units.
Stata reference · R reference
generate m = month(d)
mutate(data, m = lubridate::month(d))
lubridate
Month of a date
Stata reference · R reference
generate z = month(d)
data$z <- as.integer(format(data$d,'%m'))
base
Extract month numbers
Differs from Stata: Accepts an R Date column and returns the demonstrated calendar component; raw Stata date codes require conversion first.
Stata reference · R reference
generate q = qofd(d)
mutate(data, q = tsibble::yearquarter(d))
tsibble
Quarterly period from a date
Differs from Stata: R uses Date/POSIXct or tsibble calendar classes, not Stata numeric date/time counts from 1960; convert epochs and time zones when exchanging underlying numeric values.
Stata reference · R reference
generate z = qofd(d)
data$z <- (as.integer(format(data$d,'%Y'))-1960L)*4L+(as.integer(format(data$d,'%m'))-1L)%/%3L
base
Convert Date values to Stata quarterly codes
Differs from Stata: Returns numeric quarters since 1960q1, explicitly using Stata quarterly units.
Stata reference · R reference
generate z = quarter(d)
data$z <- (as.integer(format(data$d,'%m'))-1L)%/%3L+1L
base
Extract calendar quarter numbers
Differs from Stata: Accepts an R Date column and returns the demonstrated calendar component; raw Stata date codes require conversion first.
Stata reference · R reference
generate x = real(s)
mutate(data, x = as.numeric(s))
base
Text to a number
Differs from Stata: destring() from tidystata also strips value labels. as.numeric() warns for invalid text, unlike Stata real(); factors must be converted through their text levels before numeric conversion.
Stata reference · R reference
generate z = real(s)
valid <- grepl('^[+-]?[0-9]+([.][0-9]+)?$',data$s); data$z <- rep(NA_real_,length(valid)); data$z[valid] <- as.numeric(data$s[valid])
base
Parse a controlled decimal grammar with missing for invalid text
Differs from Stata: Deliberately limited grammar avoids accidental warnings; scientific notation and tagged missing require extension.
Stata reference · R reference
generate has = regexm(name, "^A")
mutate(data, has = str_detect(name, "^A"))
stringr
Match a regular expression
Differs from Stata: R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate z = regexm(s, "^[0-9]+$")
data$z <- as.integer(grepl('^[0-9]+$',data$s))
base
Flag strings containing only ASCII digits
Differs from Stata: This simple shared regex is portable; Stata and R regex engines differ for advanced patterns.
Stata reference · R reference
generate s = regexr(name, "[0-9]+", "")
mutate(data, s = str_replace(name, "[0-9]+", ""))
stringr
Replace the first regular-expression match
Differs from Stata: str_replace_all() replaces every match, like ustrregexra(). R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate z = regexr(s, "[0-9]+", "#")
data$z <- sub('[0-9]+','#',data$s)
base
Replace the first numeric run in text
Differs from Stata: First-match regex replacement; advanced regex features differ across engines.
Stata reference · R reference
generate z = regexreplaceall(s, "[0-9]+", "#")
data$z <- gsub('[0-9]+','#',data$s)
base
Replace all numeric runs in text
Differs from Stata: StataNow regexreplaceall workflow with a simple ASCII pattern; older Stata versions use other functions.
Stata reference · R reference
generate d = regexs(1) if regexm(name, "([0-9]+)")
mutate(data, d = str_extract(name, "[0-9]+"))
stringr
Extract the matching text
Differs from Stata: str_extract() returns NA for nonmatches; Stata generate ... if leaves empty strings in those rows. regexs() also depends on the preceding regexm() match.
Stata reference · R reference
generate z = regexs(1) if regexm(s, "([A-Z]+)-([0-9]+)")
data$z <- stringr::str_match(data$s,'([A-Z]+)-([0-9]+)')[,2]
stringr
Extract the first capturing group
R returns the group directly without a prior global regex-match state; unmatched rows use NA.
Stata reference · R reference
split name, parse(" ")
separate_wider_delim(data, name, delim = " ", names_sep = "_", too_few = "align_start")
tidyr
Split text into several variables
Stata reference · R reference
split s, parse("-") destring
data <- tidyr::separate_wider_delim(data,s,delim='-',names=c('s1','s2'),cols_remove=FALSE); data$s1 <- as.integer(data$s1); data$s2 <- as.integer(data$s2)
tidyr
Split two numeric fields and convert their types
Differs from Stata: Requires exactly two clean integer fields; resulting column names s1 and s2 are fixed.
Stata reference · R reference
split s, parse("-") generate(part)
parts <- strsplit(data$s,'-',fixed=TRUE); data$part1 <- vapply(parts,`[`,character(1),1); data$part2 <- vapply(parts,`[`,character(1),2)
base
Split two-component delimited strings
Differs from Stata: Fixed two-field example with exactly one delimiter per row; generated stub part is fixed.
Stata reference · R reference
generate z = ss(t)
data$z <- as.numeric(format(data$t,'%OS',tz='UTC'))
base
Extract seconds from a UTC timestamp
Differs from Stata: Input is an R POSIXct timestamp; fractional-second precision depends on the platform and display settings.
Stata reference · R reference
generate s = string(x)
mutate(data, s = as.character(x))
base
Number to text
Differs from Stata: tidystata's decode() uses value labels for labelled data; tostring() keeps the codes. as.character() follows R number formatting and NA handling; Stata string() uses numeric display formats and "." for numeric missing.
Stata reference · R reference
generate s = stritrim(name)
mutate(data, s = str_squish(name))
stringr
Collapse repeated spaces
Differs from Stata: str_squish() also removes leading and trailing spaces.
Stata reference · R reference
generate z = stritrim(s)
data$z <- gsub(' +',' ',data$s)
base
Collapse repeated internal ASCII spaces
Stata reference · R reference
generate n = strlen(name)
mutate(data, n = str_length(name))
stringr
Length of a string
Differs from Stata: R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate z = strlen(s)
data$z <- nchar(data$s,type='bytes')
base
Count bytes rather than Unicode characters
Differs from Stata: Byte length depends on encoding; this fixture is explicitly UTF-8.
Stata reference · R reference
generate s = strlower(name)
mutate(data, s = str_to_lower(name))
stringr
Lower case
Differs from Stata: R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate z = strlower(s)
data$z <- tolower(data$s)
base
Lowercase ASCII text
Stata reference · R reference
generate z = strltrim(s)
data$z <- sub('^ +','',data$s)
base
Trim leading ASCII spaces only
Stata reference · R reference
generate m = strmatch(name, "A*")
mutate(data, m = grepl(glob2rx("A*"), name))
utils
Match a wildcard pattern
Differs from Stata: R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate z = strmatch(s, "a*")
data$z <- as.integer(grepl(utils::glob2rx('a*'),data$s))
base
Match a simple wildcard pattern
Differs from Stata: Demonstrates * wildcard only; review escaping for more complicated patterns.
Stata reference · R reference
generate z = strofreal(x, "%06.0f")
data$z <- sprintf('%06.0f',data$x)
base
Format a number as zero-padded text
Stata reference · R reference
generate has = strpos(name, "a") > 0
mutate(data, has = str_detect(name, fixed("a")))
stringr
Whether a string contains some text
Differs from Stata: R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate z = strpos(s, "cat")
position <- regexpr('cat',data$s,fixed=TRUE); data$z <- ifelse(position<0,0L,as.integer(position))
base
Locate a literal ASCII substring with zero for absence
Stata reference · R reference
generate s = strproper(name)
mutate(data, s = str_to_title(name))
stringr
Title case
Differs from Stata: R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate z = strproper(s)
data$z <- stringr::str_to_title(data$s,locale='en')
stringr
Capitalize words in English place names
Differs from Stata: English locale example; punctuation and language-specific capitalization can differ.
Stata reference · R reference
generate z = strreverse(s)
data$z <- vapply(strsplit(data$s,''),function(z) paste(rev(z),collapse=''),character(1))
base
Reverse plain ASCII text
Stata reference · R reference
generate z = strrtrim(s)
data$z <- sub(' +$','',data$s)
base
Trim trailing ASCII spaces only
Stata reference · R reference
generate n = strtoname(s)
mutate(data, n = make.names(s))
base
Turn text into a valid name
Differs from Stata: janitor::clean_names(data) cleans every variable name at once. make.names() allows dots and follows R reserved-word rules; strtoname() follows Stata allowed-character and length limits.
Stata reference · R reference
generate z = strtoname(s)
data$z <- substr(gsub('[^A-Za-z0-9_]','_',data$s),1,32); data$z <- ifelse(grepl('^[0-9]',data$z),paste0('_',data$z),data$z)
base
Convert short ASCII text to Stata-style names
Differs from Stata: Demonstrated short ASCII names only; R syntactic names and Stata reserved names follow different rules.
Stata reference · R reference
generate s = strtrim(name)
mutate(data, s = str_trim(name))
stringr
Remove leading and trailing spaces
Differs from Stata: R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate z = strtrim(s)
data$z <- trimws(data$s,whitespace=' ')
base
Trim leading and trailing ASCII spaces
Stata reference · R reference
generate s = strupper(name)
mutate(data, s = str_to_upper(name))
stringr
Upper case
Differs from Stata: R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate z = strupper(s)
data$z <- toupper(data$s)
base
Uppercase ASCII text
Stata reference · R reference
generate s = subinstr(name, "a", "b", .)
mutate(data, s = str_replace_all(name, fixed("a"), "b"))
stringr
Replace text
Differs from Stata: stringr treats patterns as regular expressions; fixed() matches the text literally, as subinstr() does. R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate z = subinstr(s, "cat", "dog", .)
data$z <- gsub('cat','dog',data$s,fixed=TRUE)
base
Replace every literal occurrence
Stata reference · R reference
generate z = subinstr(s, "cat", "dog", 1)
data$z <- sub('cat','dog',data$s,fixed=TRUE)
base
Replace only the first literal occurrence
Stata reference · R reference
generate z = subinword(s, "cat", "dog", .)
data$z <- gsub('\\bcat\\b','dog',data$s,perl=TRUE)
base
Replace a complete word in simple ASCII text
Differs from Stata: Uses regular-expression word boundaries; delimiters and Unicode rules can differ from Stata.
Stata reference · R reference
generate s = substr(name, 1, 3)
mutate(data, s = str_sub(name, 1, 3))
stringr
Part of a string
Differs from Stata: R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate z = substr(s, -3, .)
data$z <- stringr::str_sub(data$s,-3)
stringr
Extract the last three ASCII characters
Stata reference · R reference
generate z = substr(s, 1, 3)
data$z <- substr(data$s,1,3)
base
Extract an ASCII prefix by length
Stata reference · R reference
generate z = substr(s, 3, 2)
data$z <- substr(data$s,3,4)
base
Extract ASCII text using start and length
Stata takes a length; base R substr takes an inclusive ending position.
Stata reference · R reference
generate z = uchar(code)
data$z <- vapply(data$code,intToUtf8,character(1))
base
Create characters from Unicode code points
Stata reference · R reference
generate s = upper(name)
mutate(data, s = str_to_upper(name))
stringr
Upper case
Differs from Stata: R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate z = ustrlen(s)
data$z <- nchar(data$s,type='chars')
base
Count Unicode code points
Counts code points, not visible grapheme clusters.
Stata reference · R reference
generate z = ustrlower(s)
data$z <- stringr::str_to_lower(data$s,locale='en')
stringr
Lowercase Unicode text with an explicit locale
Differs from Stata: The locale is explicitly English; choose the relevant locale for language-sensitive casing.
Stata reference · R reference
generate z = ustrnormalize(s, "nfc")
data$z <- stringi::stri_trans_nfc(data$s)
stringi
Normalize canonically equivalent Unicode text
Stata reference · R reference
generate z = ustrnormalize(s, "nfkc")
data$z <- stringi::stri_trans_nfkc(data$s)
stringi
Normalize compatibility Unicode characters
Stata reference · R reference
generate z = ustrpos(s, "猫")
position <- regexpr('\u732b',data$s,fixed=TRUE); data$z <- ifelse(position<0,0L,as.integer(position))
base
Locate a Unicode substring by code-point position
Stata reference · R reference
generate has = ustrregexm(name, "^a", 1)
mutate(data, has = str_detect(name, regex("^a", ignore_case = TRUE)))
stringr
Unicode-aware regular expression, ignoring case
Differs from Stata: stringr is Unicode-aware throughout, so the u- forms of Stata's string functions need no special version. R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate z = ustrregexm(s, "\p{L}+")
data$z <- as.integer(stringr::str_detect(data$s,'\\p{L}+'))
stringr
Detect Unicode letters
Differs from Stata: ICU regex workflow; missing strings in R remain NA rather than empty Stata strings.
Stata reference · R reference
generate z = ustrregexra(s, "[0-9]+", "#")
data$z <- stringr::str_replace_all(data$s,'[0-9]+','#')
stringr
Replace every ICU regex match
Stata reference · R reference
generate z = ustrregexrf(s, "[0-9]+", "#")
data$z <- stringr::str_replace(data$s,'[0-9]+','#')
stringr
Replace the first ICU regex match
Stata reference · R reference
generate z = ustrreverse(s)
data$z <- stringi::stri_reverse(data$s)
stringi
Reverse Unicode code-point order
Differs from Stata: Combining marks and grapheme clusters may require a different user-facing reversal rule.
Stata reference · R reference
generate z = ustrtrim(s)
data$z <- stringr::str_trim(data$s)
stringr
Trim Unicode whitespace
Stata reference · R reference
generate z = ustrupper(s)
data$z <- stringr::str_to_upper(data$s,locale='en')
stringr
Uppercase Unicode text with an explicit locale
Differs from Stata: Explicit English locale; locale-specific casing can differ from Stata defaults.
Stata reference · R reference
generate z = usubstr(s, 2, 1)
data$z <- substr(data$s,2,2)
base
Extract one Unicode code point by position
R character indexing follows code points; this does not count grapheme clusters.
Stata reference · R reference
generate w = word(name, 1)
mutate(data, w = stringr::word(name, 1))
stringr
The first word of a string
Differs from Stata: R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate z = word(s, 2)
data$z <- vapply(strsplit(trimws(data$s),' +'),function(z) z[2],character(1))
base
Extract the second simple whitespace word
Differs from Stata: Simple unquoted words with at least two tokens; Stata quoted-word parsing is not reproduced.
Stata reference · R reference
generate n = wordcount(name)
mutate(data, n = str_count(name, "\\S+"))
stringr
Number of words
Differs from Stata: R Unicode, regular-expression and case rules can differ from non-ustr Stata string functions; Stata empty strings are missing whereas R distinguishes empty strings and NA.
Stata reference · R reference
generate z = wordcount(s)
data$z <- ifelse(trimws(data$s)=='',0L,lengths(strsplit(trimws(data$s),' +')))
base
Count simple whitespace-separated words
Differs from Stata: Unquoted ASCII words only; quoted multiword phrases need a parser.
Stata reference · R reference
generate y = year(d)
mutate(data, y = lubridate::year(d))
lubridate
Year of a date
lubridate::month(), day() and wday() extract the other parts.
Stata reference · R reference
generate z = year(d)
data$z <- as.integer(format(data$d,'%Y'))
base
Extract calendar years
Differs from Stata: Accepts an R Date column and returns the demonstrated calendar component; raw Stata date codes require conversion first.
Stata reference · R reference
generate z = ym(year, month)
data$z <- (data$year-1960L)*12L+data$month-1L
base
Construct Stata monthly codes from year and month
Differs from Stata: Requires valid integer months 1–12; output uses Stata months since January 1960.
Stata reference · R reference
generate z = yq(year, quarter)
data$z <- (data$year-1960L)*4L+data$quarter-1L
base
Construct Stata quarterly codes from year and quarter
Differs from Stata: Requires valid integer quarters 1–4; output uses quarters since 1960q1.
Stata reference · R reference

Loops and programming

Stata R Purpose, qualifications and sources
ado update
update.packages()
utils
Update installed packages
Stata reference · R reference
capture command
capture(expression)
tidystata
Run code and keep its result without stopping on an error
Differs from Stata: Returns the expression's result on success; on error, emits a failure message and returns invisible NULL. quiet = TRUE suppresses the notice, warnings and messages, but keeps printed output. Use capture(data <- update(data)) to preserve an existing object if the update fails; data <- capture(update(data)) assigns NULL on error. Separate assignments in a captured block keep the last completed update; a single assignment around a failed pipeline keeps the original target. Earlier effects are not rolled back. This adapts Stata capture, which suppresses all output.
Stata reference · R reference
clear all
rm(list = ls())
base
Remove every object
Restarting R (Session > Restart R in RStudio) gives a truly clean start.
Stata reference · R reference
cls
cat("\014")
base
Clear the console
In RStudio, Ctrl+L does the same.
Stata reference · R reference
display _b[x]
coef(fit)["x"]
stats
A stored coefficient
Stata reference · R reference
display _se[x]
sqrt(diag(vcov(fit)))["x"]
stats
A stored standard error
Stata reference · R reference
ereturn list
broom::glance(fit)
broom
Model statistics
broom::tidy(fit) gives the coefficient table, and names(fit) lists every stored part.
Stata reference · R reference
foreach v of varlist v1-v5 { generate `v'_sq = `v'^2 }
mutate(data, across(v1:v5, ~ .x^2, .names = "{col}_sq"))
dplyr
Same calculation for several variables
across() replaces most variable loops; for other loops R has for (v in names) { ... }.
Stata reference · R reference
forvalues i = 1/5 { generate v`i'_sq = v`i'^2 if v`i' > 0 }
mutate(data, across(v1:v5, ~ if_else(.x > 0, .x^2, NA), .names = "{col}_sq"))
dplyr
Loop with a condition
Stata reference · R reference
forvalues i = 6/10 { forvalues j = 3/5 { replace x_`i'_`j' = x_`i'_`j' + 1 } }
mutate(data, across(matches("^x_([6-9]|10)_[3-5]$"), ~ .x + 1))
dplyr
Loop over variables numbered in their names
A regular expression picks the names. varlist("x_[6-10]_*") works when only one number range is needed.
Stata reference · R reference
frame create other
other <- tibble()
tibble
Hold another dataset
R keeps any number of data frames as separate objects, so frames are built in.
Stata reference · R reference
if `x' > 0 { display "positive" }
if (x > 0) print("positive")
base
Run code only if a condition holds
Quote it: findit("if"), because if is a reserved word in R.
Stata reference · R reference
local vars x1 x2 x3
vars <- c("x1", "x2", "x3")
base
Store a list of variable names
Use it with all_of(): select(data, all_of(vars)) or across(all_of(vars), ...).
Stata reference · R reference
macro list
ls()
base
List defined objects
Stata reference · R reference
matrix A = (1, 2 \ 3, 4)
A <- matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE)
base
Create a matrix
Stata reference · R reference
preserve
backup <- data
base
Keep a copy to return to
R never changes data in place, so keep the original object and assign results to a new name; restore is data <- backup.
Stata reference · R reference
program define myprog
myprog <- function(data) { summ(data) }
base
Write your own command
Stata reference · R reference
quietly regress y x
fit <- lm(y ~ x, data = data)
stats
Run without printing
Assigning a result never prints it; print(fit) or summary(fit) shows it later.
Stata reference · R reference
return list
str(summ(data, x))
tidystata
See the results a command stored
R results are ordinary objects: assign them and pick out parts, as in s <- summ(data, x); s$mean.
Stata reference · R reference
scalar a = 3
a <- 3
base
Store a single number
Stata reference · R reference
set seed 2024
set.seed(2024)
base
Make random numbers reproducible
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.
Stata reference · R reference
set trace on
traceback()
base
Find where an error happened
debug(f) or browser() steps through a function line by line.
Stata reference · R reference
tempfile f
f <- tempfile(fileext = ".rds")
base
A temporary file
Temporary variables are not needed: intermediate columns can be dropped, or kept as separate objects.
Stata reference · R reference
timer on 1
timer(expression)
tidystata
Time how long code takes
Stata reference · R reference
version 18
R.version.string
base
Version control
renv::snapshot() records package versions so a project can be reproduced later.
Stata reference · R reference
which summarize
getAnywhere("summ")
utils
Where a command comes from
Stata reference · R reference
while `i' < 10 { local i = `i' + 1 }
while (i < 10) { i <- i + 1 }
base
Repeat while a condition holds
Stata reference · R reference

Models and tables

Stata R Purpose, qualifications and sources
areg y x, absorb(id)
fixest::feols(y ~ x | id, data = data)
fixest
Regression absorbing one categorical variable
Differs from Stata: Match fixest covariance small-sample corrections and singleton handling with Stata; the same formula does not guarantee identical standard errors or retained observations.
Stata reference · R reference
avplots
car::avPlots(fit)
car
Added-variable plots
Stata reference · R reference
bootstrap, reps(500): regress y x
lmtest::coeftest(fit, vcov = sandwich::vcovBS(fit, R = 500))
sandwich
Bootstrap standard errors
Differs from Stata: The R code estimates covariance for an existing fit; resampling units, centering and t/normal inference must match the Stata bootstrap/jackknife prefix options.
Stata reference · R reference
cluster kmeans x1 x2, k(3)
kmeans(na.omit(select(data, x1, x2)), centers = 3)
stats
K-means clustering
Differs from Stata: R defaults to Hartigan-Wong k-means and random initial centers; Stata initialization and iteration defaults differ. Control the starting centers to compare clusters.
Stata reference · R reference
csdid y, ivar(id) time(year) gvar(first_treat)
did::att_gt(yname = "y", tname = "year", idname = "id", gname = "first_treat", data = data)
did
Staggered difference in differences
Differs from Stata: Match control-group, anticipation and estimation-method settings; csdid and att_gt() defaults and aggregation/inference need not coincide.
Stata reference · R reference
didregress (y) (treated), group(id) time(year)
fixest::feols(y ~ treated | id + year, data = data)
fixest
Difference in differences (Stata 17+)
Differs from Stata: The TWFE coefficient alone omits didregress default group-clustered standard errors and diagnostics; specify clustering and verify the DID design.
Stata reference · R reference
estat hettest
lmtest::bptest(fit, ~ fitted(fit), studentize = FALSE)
lmtest
Breusch-Pagan test for heteroskedasticity
These options match Stata's default test against the fitted values.
Stata reference · R reference
estat ic
c(AIC = AIC(fit), BIC = BIC(fit))
stats
Information criteria
Differs from Stata: Compare the same fitted sample and likelihood constants; R classes and Stata can count scale parameters and likelihood terms differently.
Stata reference · R reference
estat ovtest
lmtest::resettest(fit, power = 2:4)
lmtest
RESET test for omitted variables
Stata reference · R reference
estat vce
vcov(fit)
stats
Variance-covariance matrix
Stata reference · R reference
estimates store m1
m1 <- lm(y ~ x, data = data)
stats
Keep a model for later
A fitted model is an ordinary object; keep as many as you like under different names.
Stata reference · R reference
estimates table m1 m2
modelsummary::modelsummary(list(m1, m2), output = "markdown")
modelsummary
Compare models side by side
Stata reference · R reference
eststo m1: regress y x
m1 <- lm(y ~ x, data = data)
stats
Store a model for a table
Stata reference · R reference
esttab m1 m2
modelsummary::modelsummary(list(m1, m2))
modelsummary
Regression table
Stata reference · R reference
etable
modelsummary::modelsummary(fit)
modelsummary
Table of the last model (Stata 17+)
Stata reference · R reference
glm y x, family(binomial)
glm(y ~ x, family = binomial, data = data)
stats
Generalised linear model
Stata reference · R reference
heckman y x, select(s = z)
sampleSelection::selection(s ~ z, y ~ x, data = data)
sampleSelection
Heckman selection model
Stata reference · R reference
ivreg2 y x1 (x2 = z), robust
fixest::feols(y ~ x1 | x2 ~ z, data = data, vcov = "hetero")
fixest
Instrumental variables with robust errors
Differs from Stata: fixest::fitstat(fit, ~ ivf + ivwald) reports first-stage statistics. Match fixest covariance small-sample corrections and singleton handling with Stata; the same formula does not guarantee identical standard errors or retained observations.
Stata reference · R reference
ivregress 2sls y x1 (x2 = z)
fixest::feols(y ~ x1 | x2 ~ z, data = data)
fixest
Instrumental variables (2SLS)
Differs from Stata: Match fixest covariance small-sample corrections and singleton handling with Stata; the same formula does not guarantee identical standard errors or retained observations.
Stata reference · R reference
jackknife: regress y x
lmtest::coeftest(fit, vcov = sandwich::vcovJK(fit))
sandwich
Jackknife standard errors
Differs from Stata: The R code estimates covariance for an existing fit; resampling units, centering and t/normal inference must match the Stata bootstrap/jackknife prefix options.
Stata reference · R reference
lincom x1 - x2
marginaleffects::hypotheses(fit, "x1 - x2 = 0")
marginaleffects
Linear combination of coefficients
Differs from Stata: hypotheses() uses the fitted R covariance and degrees-of-freedom defaults; Stata can use a different t, F or normal reference distribution.
Stata reference · R reference
logistic y x
broom::tidy(glm(y ~ x, family = binomial, data = data), exponentiate = TRUE, conf.int = TRUE)
broom
Logit model reported as odds ratios
Differs from Stata: broom confidence intervals are model-specific; glm profile-likelihood intervals can differ from Stata default Wald intervals, even when odds ratios agree.
Stata reference · R reference
logit y x1 x2
glm(y ~ x1 + x2, family = binomial, data = data)
stats
Logit model
Stata reference · R reference
logit y x, or
broom::tidy(glm(y ~ x, family = binomial, data = data), exponentiate = TRUE)
broom
Odds ratios
Differs from Stata: broom confidence intervals are model-specific; glm profile-likelihood intervals can differ from Stata default Wald intervals, even when odds ratios agree.
Stata reference · R reference
lrtest m1 m2
lmtest::lrtest(m1, m2)
lmtest
Likelihood-ratio test
Differs from Stata: Compare the same fitted sample and likelihood constants; R classes and Stata can count scale parameters and likelihood terms differently.
Stata reference · R reference
margins group
marginaleffects::avg_predictions(fit, by = "group")
marginaleffects
Predictive margins by group
Differs from Stata: by = "group" averages within observed groups; margins group sets each level for every observation before averaging. Use counterfactual predictions for that Stata estimand.
Stata reference · R reference
margins, dydx(*)
marginaleffects::avg_slopes(fit)
marginaleffects
Average marginal effects
Differs from Stata: avg_slopes() averages model derivatives; discrete factor changes, weights and covariance must match margins and the fitted-model context.
Stata reference · R reference
marginsplot
marginaleffects::plot_predictions(fit, condition = "x")
marginaleffects
Plot predictive margins
Stata reference · R reference
melogit y x || id:
lme4::glmer(y ~ x + (1 | id), data = data, family = binomial)
lme4
Multilevel logit
Differs from Stata: glmer() defaults to Laplace integration (nAGQ = 1); melogit defaults to adaptive quadrature, which can change estimates and likelihoods.
Stata reference · R reference
mi estimate: regress y x
mice::pool(with(imp, lm(y ~ x)))
mice
Fit and combine models across imputations
Differs from Stata: Rubin pooling still requires matching complete-data degrees of freedom and small-sample adjustments to mi estimate.
Stata reference · R reference
mi impute chained (regress) x1 x2 = y
imp <- mice::mice(data, m = 20)
mice
Multiple imputation
Differs from Stata: mice() chooses methods by R column type, often predictive mean matching; it does not default to the specified chained linear regressions. Match methods, predictors and m explicitly.
Stata reference · R reference
mixed y x || id:
lme4::lmer(y ~ x + (1 | id), data = data)
lme4
Multilevel (mixed) linear model
Differs from Stata: lme4 reports no p-values; lmerTest::lmer() adds them. lmer() defaults to REML; Stata mixed defaults to ML. Use REML = FALSE for ML and select a separate method for fixed-effect p-values.
Stata reference · R reference
mlogit y x1 x2
nnet::multinom(y ~ x1 + x2, data = data)
nnet
Multinomial logit
Differs from Stata: multinom() needs a factor y for multinomial classification; reference outcome categories and optimizer defaults can differ from Stata mlogit.
Stata reference · R reference
nbreg y x
MASS::glm.nb(y ~ x, data = data)
MASS
Negative binomial model
Differs from Stata: fixest::fenegbin() adds fixed effects. glm.nb() uses NB2 like default nbreg, but theta is the reciprocal of Stata alpha and likelihood/optimization reporting differs.
Stata reference · R reference
nlcom _b[x1] / _b[x2]
marginaleffects::hypotheses(fit, "x1 / x2 = 0")
marginaleffects
Nonlinear combination of coefficients
Differs from Stata: Standard errors use the delta method, as in Stata. hypotheses() uses the fitted R covariance and degrees-of-freedom defaults; Stata can use a different t, F or normal reference distribution.
Stata reference · R reference
oaxaca y x1 x2, by(group)
oaxaca::oaxaca(y ~ x1 + x2 | group, data = data)
oaxaca
Blinder-Oaxaca decomposition
Differs from Stata: oaxaca() reports several reference-weight decompositions; explicitly select the reference coefficients and variance method used by Stata oaxaca.
Stata reference · R reference
ologit y x1 x2
MASS::polr(factor(y) ~ x1 + x2, data = data, Hess = TRUE)
MASS
Ordered logit
Differs from Stata: Hess = TRUE lets summary() show standard errors. polr() uses ordered factor levels and a threshold parameterization; set the order explicitly and check the cutpoint sign convention against Stata.
Stata reference · R reference
oprobit y x1 x2
MASS::polr(factor(y) ~ x1 + x2, data = data, method = "probit", Hess = TRUE)
MASS
Ordered probit
Differs from Stata: polr() uses ordered factor levels and a threshold parameterization; set the order explicitly and check the cutpoint sign convention against Stata.
Stata reference · R reference
outreg2 using table.doc
modelsummary::modelsummary(list(m1, m2), output = "table.docx")
modelsummary
Regression table in a Word file
Stata reference · R reference
poisson y x1 x2
glm(y ~ x1 + x2, family = poisson, data = data)
stats
Poisson model
Stata reference · R reference
ppmlhdfe y x, absorb(id year)
fixest::fepois(y ~ x | id + year, data = data)
fixest
Poisson model with fixed effects
Differs from Stata: Poisson fixed-effect coefficient targets agree, but separation/singleton removal and covariance corrections can differ; check the retained sample and uncertainty.
Stata reference · R reference
predict yhat
mutate(data, yhat = predict(fit, newdata = data))
stats
Fitted values
Differs from Stata: residuals(fit) gives residuals for the rows used in the model. predict() depends on the R model: response/link scale, residual definition and prediction sample must match the Stata postestimation context.
Stata reference · R reference
predict p, pr
mutate(data, p = predict(fit, newdata = data, type = "response"))
stats
Predicted probabilities
Differs from Stata: predict() depends on the R model: response/link scale, residual definition and prediction sample must match the Stata postestimation context.
Stata reference · R reference
predict r, residuals
mutate(data, r = y - predict(fit, newdata = data))
stats
Residuals for every row
Differs from Stata: predict() depends on the R model: response/link scale, residual definition and prediction sample must match the Stata postestimation context.
Stata reference · R reference
probit y x1 x2
glm(y ~ x1 + x2, family = binomial(link = "probit"), data = data)
stats
Probit model
Stata reference · R reference
putdocx begin
flextable::save_as_docx(flextable::flextable(results), path = "results.docx")
flextable
Write a table to Word
officer builds whole Word documents.
Stata reference · R reference
putexcel set results.xlsx
writexl::write_xlsx(results, "results.xlsx")
writexl
Write results to Excel
openxlsx2 gives cell-level control over formatting.
Stata reference · R reference
qreg y x
quantreg::rq(y ~ x, tau = 0.5, data = data)
quantreg
Median (quantile) regression
Differs from Stata: rq() default standard-error methods depend on sample size and can differ from Stata qreg; choose the covariance/inference method explicitly.
Stata reference · R reference
rdrobust y x, c(0)
rdrobust::rdrobust(data$y, data$x, c = 0)
rdrobust
Regression discontinuity
Differs from Stata: The R and Stata implementations share the estimator; version, bandwidth, mass-point and variance settings must also match for finite-sample output.
Stata reference · R reference
reghdfe y x, absorb(id year)
fixest::feols(y ~ x | id + year, data = data)
fixest
High-dimensional fixed effects
Differs from Stata: Match fixest covariance small-sample corrections and singleton handling with Stata; the same formula does not guarantee identical standard errors or retained observations.
Stata reference · R reference
regress y x1 x2
fit <- lm(y ~ x1 + x2, data = data)
stats
Linear regression
summary(fit) shows the coefficient table; broom::tidy(fit) returns it as a data frame.
Stata reference · R reference
regress y i.group c.x1##c.x2
lm(y ~ factor(group) + x1 * x2, data = data)
stats
Factor variables and interactions
Differs from Stata: factor() plays the role of i.; x1 * x2 is c.x1##c.x2 and x1:x2 is c.x1#c.x2. factor() chooses its reference from R level order; Stata i.group uses its numeric base level. Set factor levels and contrasts explicitly.
Stata reference · R reference
regress y ib3.group
lm(y ~ relevel(factor(group), ref = "3"), data = data)
stats
Choose the base category
Stata reference · R reference
regress y x [pweight = wt]
fixest::feols(y ~ x, data = data, weights = ~wt, vcov = "hetero")
fixest
Regression with sampling weights
Differs from Stata: For full survey designs with strata and clusters, see svyset. Match fixest covariance small-sample corrections and singleton handling with Stata; the same formula does not guarantee identical standard errors or retained observations.
Stata reference · R reference
regress y x1 x2, robust
fixest::feols(y ~ x1 + x2, data = data, vcov = "hetero")
fixest
Heteroskedasticity-robust standard errors
Differs from Stata: Match fixest covariance small-sample corrections and singleton handling with Stata; the same formula does not guarantee identical standard errors or retained observations.
Stata reference · R reference
regress y x1 x2, vce(cluster id)
fixest::feols(y ~ x1 + x2, data = data, cluster = ~id)
fixest
Clustered standard errors
Differs from Stata: Match fixest covariance small-sample corrections and singleton handling with Stata; the same formula does not guarantee identical standard errors or retained observations.
Stata reference · R reference
rreg y x
MASS::rlm(y ~ x, data = data)
MASS
Robust regression
Differs from Stata: rlm() uses Huber M-estimation; Stata's rreg combines Huber and biweight steps, so estimates can differ slightly. rlm() defaults to Huber M-estimation; rreg screens outliers and combines Huber and biweight iterations, so estimates and inference can differ.
Stata reference · R reference
rvfplot
plot(fit, which = 1)
stats
Residuals against fitted values
Stata reference · R reference
sem (y <- x1 x2)
lavaan::sem("y ~ x1 + x2", data = data)
lavaan
Structural equation model
Differs from Stata: lavaan treats observed exogenous predictors as fixed by default; match fixed.x and missing-data likelihood settings with Stata sem.
Stata reference · R reference
synth y x1 x2, trunit(1) trperiod(2000)
Synth::synth(data.prep.obj = prep)
Synth
Synthetic control
Synth::dataprep() builds prep from the panel first; tidysynth offers a tidier interface.
Stata reference · R reference
teffects ipw (y) (t x1 x2)
WeightIt::weightit(t ~ x1 + x2, data = data, method = "glm")
WeightIt
Inverse-probability weighting
Stata reference · R reference
teffects psmatch (y) (t x1 x2)
MatchIt::matchit(t ~ x1 + x2, data = data, method = "nearest")
MatchIt
Propensity-score matching
Estimate the effect on the matched data, for example lm(y ~ t, data = MatchIt::match.data(m), weights = weights).
Stata reference · R reference
test x1 = x2
marginaleffects::hypotheses(fit, "x1 = x2")
marginaleffects
Test a hypothesis about coefficients
Differs from Stata: hypotheses() uses the fitted R covariance and degrees-of-freedom defaults; Stata can use a different t, F or normal reference distribution.
Stata reference · R reference
tobit y x, ll(0)
AER::tobit(y ~ x, left = 0, data = data)
AER
Censored (tobit) regression
Stata reference · R reference
vif
car::vif(fit)
car
Variance inflation factors
Differs from Stata: car::vif() gives generalized VIFs for multi-degree-of-freedom terms; Stata estat vif reports regressor-column VIFs, so factor-term tables differ.
Stata reference · R reference
xtabond y x
plm::pgmm(y ~ lag(y, 1) + x | lag(y, 2:99), data = data, index = c("id", "year"))
plm
Dynamic panel (Arellano-Bond)
Differs from Stata: pgmm() needs matching transformation, lag instruments, collapse and one/two-step choices; the formula alone does not reproduce xtabond default instruments or standard errors.
Stata reference · R reference
xtlogit y x, fe
survival::clogit(y ~ x + strata(id), data = data)
survival
Conditional (fixed-effects) logit
Differs from Stata: fixest::feglm(y ~ x | id, family = binomial) is faster but estimates unconditional fixed effects. clogit() targets conditional fixed-effects logit; exact likelihood, weights and covariance settings must match xtlogit, fe rather than unconditional dummy-variable logit.
Stata reference · R reference
xtpoisson y x, fe
fixest::fepois(y ~ x | id, data = data)
fixest
Fixed-effects Poisson
Differs from Stata: Poisson fixed-effect coefficient targets agree, but separation/singleton removal and covariance corrections can differ; check the retained sample and uncertainty.
Stata reference · R reference
xtreg y x, fe
fixest::feols(y ~ x | id, data = data)
fixest
Panel fixed effects
Differs from Stata: Match fixest covariance small-sample corrections and singleton handling with Stata; the same formula does not guarantee identical standard errors or retained observations.
Stata reference · R reference
xtreg y x, re
plm::plm(y ~ x, data = data, index = c("id", "year"), model = "random")
plm
Panel random effects
Differs from Stata: plm and xtreg, re default to different variance-component estimators; match random.method and the panel sample before comparing results.
Stata reference · R reference

Panel and time series

Stata R Purpose, qualifications and sources
arima y, ar(1/2)
arima(data$y, order = c(2, 0, 0))
stats
ARIMA model
Differs from Stata: R and Stata ARIMA initialization and intercept parameterizations differ; match the likelihood method and transform intercepts before comparing coefficients.
Stata reference · R reference
carryforward x, replace
tidyr::fill(data, x, .direction = "down")
tidyr
Carry the last observed value forward
Differs from Stata: group_by(data, id) first to fill within each panel unit. fill() crosses panel boundaries unless grouped first; group_by(id) is needed for within-unit carryforward.
Stata reference · R reference
generate d_x = D.x
mutate(data, d_x = stata_diff(x, time = year), .by = id)
tidystata
First difference within each panel
stata_diff(x, 2, time = year) is D2.x, the difference of differences.
Stata reference · R reference
generate lead_x = F.x
mutate(data, lead_x = stata_lead(x, time = year), .by = id)
tidystata
Lead within each panel
Gaps in year give missing values, as in Stata.
Stata reference · R reference
generate lag_x = L.x
mutate(data, lag_x = stata_lag(x, time = year), .by = id)
tidystata
Lag within each panel
Like Stata, gaps in year give missing values; dplyr::lag() shifts rows instead. Use stata_lag(x, 2, time = year) for L2.x and unit = "month" for monthly dates.
Stata reference · R reference
generate lag2_x = L2.x
mutate(data, lag2_x = lag(x, 2, order_by = year), .by = id)
dplyr
Two-period lag within each panel
Differs from Stata: lag(x, 2, order_by = year) shifts two observed rows; L2.x shifts two time units and returns missing across time gaps. Use stata_lag(x, 2, time = year) for that rule.
Stata reference · R reference
tsfill
tsibble::fill_gaps(ts_data)
tsibble
Add rows for missing time points
Differs from Stata: fill_gaps() fills each key's observed range by default; choose .full explicitly for common panel bounds and ensure the tsibble interval matches the Stata delta.
Stata reference · R reference
tsline y
ggplot(data, aes(year, y)) + geom_line()
ggplot2
Time-series line plot
Stata reference · R reference
tsset year
tsibble::as_tsibble(data, index = year)
tsibble
Declare time-series data
Stata reference · R reference
xtdescribe
count(count(data, id, name = "periods"), periods)
dplyr
How many periods each panel unit has
Stata reference · R reference
xtline y
ggplot(data, aes(year, y)) + geom_line() + facet_wrap(~id)
ggplot2
One line plot per panel unit
aes(group = id) without facets draws all units in one plot, like the overlay option.
Stata reference · R reference
xtset id year
tsibble::as_tsibble(data, key = id, index = year)
tsibble
Declare panel data
tidystata needs no declaration: stata_lag(x, time = year) with .by = id, and fixest takes panel.id = ~id + year.
Stata reference · R reference
xtsum x
data |> mutate(m = mean(x, na.rm = TRUE), .by = id) |> summarise(overall = sd(x, na.rm = TRUE), within = sd(x - m, na.rm = TRUE))
dplyr
Overall and within standard deviations
The between part is the standard deviation of the id means: summarise(data, m = mean(x, na.rm = TRUE), .by = id) then sd(m).
Stata reference · R reference

Survival analysis

Stata R Purpose, qualifications and sources
estat concordance
survival::concordance(fit)
survival
Censored-outcome concordance after Cox regression
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Censoring weights and handling of tied risks/times affect the statistic.
Stata reference · R reference
estat phtest, detail
survival::cox.zph(fit, transform = "identity")
survival
Cox proportional-hazards diagnostic
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Schoenfeld-residual implementation and default time transformations differ.
Stata reference · R reference
ltable time event, intervals(0 2 4 6)
{ ends <- c(2, 4, 6); starts <- c(0, 2, 4); n <- vapply(starts, function(t) sum(data$time >= t), integer(1)); d <- vapply(seq_along(ends), function(i) sum(data$time >= starts[i] & data$time < ends[i] & data$event == 1), integer(1)); w <- vapply(seq_along(ends), function(i) sum(data$time >= starts[i] & data$time < ends[i] & data$event == 0), integer(1)); q <- d / (n - w / 2); data.frame(start = starts, end = ends, at_risk = n, failures = d, withdrawals = w, survival = cumprod(1 - q)) }
base
Actuarial life-table survival over fixed intervals
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Uses the half-withdrawal actuarial adjustment and left-closed intervals; censoring is assumed uniform within each interval. Boundary conventions and intervals must match.
Stata reference · R reference
predict baseS, basesurv
{ h <- survival::basehaz(fit, centered = FALSE); data.frame(time = h$time, survival = exp(-h$hazard)) }
survival
Baseline Cox survival from cumulative hazard
Fixed workflow; adapt the named data columns explicitly. Baseline refers to zero covariates; verify the intended reference profile. Stata basesurv uses a product-limit construction, so exp(-cumulative hazard) is an alternative estimate rather than exact numerical parity.
Stata reference · R reference
predict basehaz, basechazard
survival::basehaz(fit, centered = FALSE)
survival
Baseline cumulative hazard at zero covariates
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Cox baseline is centered at zero explicitly; Stata stores results on observation rows whereas R returns unique event/censoring times.
Stata reference · R reference
predict median_time, median
stats::predict(fit, type = "quantile", p = .5)
survival
Conditional median survival after loglogistic AFT
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Distribution-specific predicted survival quantiles; not the mean time.
Stata reference · R reference
predict residual*, deviance
stats::residuals(fit, type = "deviance")
survival
Deviance residuals after Cox regression
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Schoenfeld residuals have one row per event; score/influence residuals have one row per observation.
Stata reference · R reference
predict residual*, dfbeta
stats::residuals(fit, type = "dfbeta")
survival
Cox coefficient influence residuals
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Schoenfeld residuals have one row per event; score/influence residuals have one row per observation.
Stata reference · R reference
predict residual*, mgale
stats::residuals(fit, type = "martingale")
survival
Martingale residuals after Cox regression
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Schoenfeld residuals have one row per event; score/influence residuals have one row per observation.
Stata reference · R reference
predict residual*, scaledsch
stats::residuals(fit, type = "scaledsch")
survival
Scaled Schoenfeld residuals
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Schoenfeld residuals have one row per event; score/influence residuals have one row per observation.
Stata reference · R reference
predict residual*, schoenfeld
stats::residuals(fit, type = "schoenfeld")
survival
Event-specific Schoenfeld residuals
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Schoenfeld residuals have one row per event; score/influence residuals have one row per observation.
Stata reference · R reference
predict residual*, scores
stats::residuals(fit, type = "score")
survival
Cox score contributions
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Schoenfeld residuals have one row per event; score/influence residuals have one row per observation.
Stata reference · R reference
predict value, csnell
stats::predict(fit, type = "expected", reference = "zero")
survival
Cox-Snell expected-event quantities
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Centering is explicitly zero for relative predictions; expected-event quantities depend on each observed follow-up time.
Stata reference · R reference
predict value, hr
stats::predict(fit, type = "risk", reference = "zero")
survival
Cox relative-hazard scores
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Centering is explicitly zero for relative predictions; expected-event quantities depend on each observed follow-up time.
Stata reference · R reference
predict value, xb
stats::predict(fit, type = "lp", reference = "zero")
survival
Cox linear predictors
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Centering is explicitly zero for relative predictions; expected-event quantities depend on each observed follow-up time.
Stata reference · R reference
snapspan id time event, generate(start)
{ out <- data[order(data$id, data$time), ]; previous <- ave(out$time, out$id, FUN = function(v) c(NA_real_, head(v, -1))); previous_x <- ave(out$x, out$id, FUN = function(v) c(NA_real_, head(v, -1))); out$start <- previous; out$x <- previous_x; out[!is.na(out$start), ] }
stats
Convert snapshots to intervals with covariates applying forward
Fixed workflow; adapt the named data columns explicitly. The first snapshot defines interval entry, event indicators apply at interval exit, and ordinary covariates apply forward. This explicit workflow drops initial zero-duration rows; check Stata's retained baseline rows before matching row counts.
Stata reference · R reference
stbase
data[order(data$id, data$start), ][!duplicated(data[order(data$id, data$start), "id"]), ]
base
Keep baseline record for each subject
Fixed workflow; adapt the named data columns explicitly. Record-selection workflow only; stbase may also transform survival-time fields.
Stata reference · R reference
stci, median
stats::quantile(survival::survfit(s ~ 1), probs = .5)
survival
Median survival with confidence limits
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Median interpolation and confidence-limit conventions can differ.
Stata reference · R reference
stci, rmean
summary(survival::survfit(s ~ 1), rmean = "common")$table
survival
Restricted mean survival through time nine
Differs from Stata: rmean="common" restricts the survival integral at the largest observed follow-up time, as Stata stci, rmean does; it does not extrapolate beyond follow-up. Match the analysis sample and censoring declaration.
Stata reference · R reference
stcox x1 x2
survival::coxph(survival::Surv(time, died) ~ x1 + x2, data = data)
survival
Cox proportional hazards model
Differs from Stata: exp(coef(fit)) gives the hazard ratios that stcox reports. coxph() defaults to Efron handling of ties; Stata stcox defaults to Breslow. Set ties = "breslow" to match tied-event likelihoods.
Stata reference · R reference
stcox c.x##i.group
survival::coxph(survival::Surv(time, event) ~ x * factor(group), ties = "breslow", data = data)
survival
Cox treatment-covariate interaction
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match ties, risk intervals, weights and reference inference explicitly.
Stata reference · R reference
stcox x z
survival::coxph(survival::Surv(time, event) ~ x + z, data = data, ties = "breslow")
survival
Cox regression with Breslow ties
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match ties, risk intervals, weights and reference inference explicitly.
Stata reference · R reference
stcox x z [pw=w], vce(robust)
survival::coxph(survival::Surv(time, event) ~ x + z, ties = "breslow", data = data, weights = w, robust = TRUE)
survival
Weighted Cox model with sandwich covariance
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match ties, risk intervals, weights and reference inference explicitly.
Stata reference · R reference
stcox x z, efron
survival::coxph(survival::Surv(time, event) ~ x + z, data = data, ties = "efron")
survival
Cox regression with Efron ties
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match ties, risk intervals, weights and reference inference explicitly.
Stata reference · R reference
stcox x z, exactp
survival::coxph(survival::Surv(time, event) ~ x + z, data = data, ties = "exact")
survival
Cox regression with exact partial likelihood
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match ties, risk intervals, weights and reference inference explicitly.
Stata reference · R reference
stcox x z, shared(id)
survival::coxph(survival::Surv(time, event) ~ x + z + frailty(id, distribution = "gamma"), ties = "breslow", data = data)
survival
Shared gamma frailty Cox model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match ties, risk intervals, weights and reference inference explicitly.
Stata reference · R reference
stcox x z, strata(group)
survival::coxph(survival::Surv(time, event) ~ x + z + strata(group), ties = "breslow", data = data)
survival
Stratified Cox baseline hazards
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match ties, risk intervals, weights and reference inference explicitly.
Stata reference · R reference
stcox x z, vce(cluster id)
survival::coxph(survival::Surv(time, event) ~ x + z, ties = "breslow", data = data, cluster = id)
survival
Cluster-robust Cox inference
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match ties, risk intervals, weights and reference inference explicitly.
Stata reference · R reference
stcox x, tvc(z) texp(ln(_t))
survival::coxph(survival::Surv(time, event) ~ x + tt(z), ties = "breslow", data = data, tt = function(z, t, ...) z * log(t))
survival
Cox time-varying log-time coefficient
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match ties, risk intervals, weights and reference inference explicitly.
Stata reference · R reference
stcrreg x z, compete(cause==2)
{ expanded <- survival::finegray(survival::Surv(time, cause) ~ x + z + id, data = data, etype = "target"); survival::coxph(survival::Surv(fgstart, fgstop, fgstatus) ~ x + z, data = expanded, weights = fgwt, cluster = id) }
survival
Fine-Gray subdistribution-hazard workflow
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Weighted expanded-data implementation; censoring weights and variance choices can differ.
Stata reference · R reference
stdescribe
data.frame(subjects = nrow(data), failures = sum(data$event), time_at_risk = sum(data$time))
base
Describe single-record survival data
Fixed workflow; adapt the named data columns explicitly. Single-record, zero-entry fixture; multiple-record subjects require distinct-ID counting.
Stata reference · R reference
stfill z, forward
{ out <- data[order(data$id, data$start), ]; out$z <- ave(out$z, out$id, FUN = function(v) zoo::na.locf(v, na.rm = FALSE)); out }
zoo
Carry observed covariates forward within survival subjects
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Requires correctly ordered non-overlapping spells. Leading missing values remain missing; later information is never carried backward.
Stata reference · R reference
stgen ever_x = ever(x==1)
transform(data, ever_x = ave(x == 1, id, FUN = function(v) as.integer(any(v))))
stats
Mark subjects ever exposed during their observed survival history
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. All observed spells contribute to the history. Missing exposure values require an explicit convention rather than treating NA as false.
Stata reference · R reference
stintreg x, interval(lower upper) distribution(lognormal)
survival::survreg(survival::Surv(lower, upper, type = "interval2") ~ x, data = data, dist = "lognormal")
survival
Lognormal regression for interval-censored outcomes
Differs from Stata: Stata requires interval(lower upper). The Weibull time option selects AFT coefficients, matching survreg rather than Stata default PH coefficients. For interval2, equal endpoints are exact events, NA lower endpoints denote left censoring, and NA upper endpoints right censoring; encode Stata left-censoring bounds explicitly.
Stata reference · R reference
stintreg x, interval(lower upper) distribution(weibull) time
survival::survreg(survival::Surv(lower, upper, type = "interval2") ~ x, data = data, dist = "weibull")
survival
Weibull regression for interval-censored outcomes
Differs from Stata: Stata requires interval(lower upper). The Weibull time option selects AFT coefficients, matching survreg rather than Stata default PH coefficients. For interval2, equal endpoints are exact events, NA lower endpoints denote left censoring, and NA upper endpoints right censoring; encode Stata left-censoring bounds explicitly.
Stata reference · R reference
stir group
{ counts <- tapply(data$event, data$group, sum); times <- tapply(data$time, data$group, sum); stats::poisson.test(counts, T = times) }
stats
Compare two incidence rates
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R gives a conditional exact test and interval; Stata default intervals may use a different method.
Stata reference · R reference
stjoin
{ out <- stats::aggregate(cbind(time = time - start, event) ~ id, data = spells, sum); names(out)[2] <- "duration"; out }
stats
Rejoin adjacent constant-covariate spells
Fixed workflow; adapt the named data columns explicitly. Only valid when adjacent spells have identical covariates and no intervening event; inspect before collapsing.
Stata reference · R reference
stmh exposed stratum
with(data, sum(events1 * time0 / (time1 + time0)) / sum(events0 * time1 / (time1 + time0)))
base
Mantel-Haenszel stratified incidence-rate-ratio point estimate
Fixed workflow; adapt the named data columns explicitly. Input is pre-aggregated failure counts and person-time by exposure/stratum. This supplies the rate-ratio point estimate only, not Stata's variance or trend tests.
Stata reference · R reference
stptime
{ pt <- sum(data$time); events <- sum(data$event); c(person_time = pt, failures = events, rate = events / pt) }
base
Crude incidence rate from person-time
Fixed workflow; adapt the named data columns explicitly. Assumes zero entry times and non-overlapping observation spells.
Stata reference · R reference
strate group, per(1000)
{ out <- stats::aggregate(cbind(time, event) ~ group, data, sum); out$rate_per_1000 <- 1000 * out$event / out$time; out }
stats
Group-specific rates per thousand person-time units
Fixed workflow; adapt the named data columns explicitly. Point-rate workflow; confidence intervals need a separate choice.
Stata reference · R reference
streg x, distribution(weibull)
survival::survreg(survival::Surv(time, died) ~ x, data = data, dist = "weibull")
survival
Parametric survival model
Differs from Stata: survreg() reports the accelerated failure-time form; Stata's Weibull default is the hazard form, so signs and scales differ.
Stata reference · R reference
streg x z, distribution(exponential) time
survival::survreg(survival::Surv(time, event) ~ x + z, data = data, dist = "exponential")
survival
exponential accelerated-failure-time model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. survreg reports AFT coefficients; Weibull PH coefficients require sign and scale conversion.
Stata reference · R reference
streg x z, distribution(loglogistic) time
survival::survreg(survival::Surv(time, event) ~ x + z, data = data, dist = "loglogistic")
survival
loglogistic accelerated-failure-time model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. survreg reports AFT coefficients; Weibull PH coefficients require sign and scale conversion.
Stata reference · R reference
streg x z, distribution(lognormal) time
survival::survreg(survival::Surv(time, event) ~ x + z, data = data, dist = "lognormal")
survival
lognormal accelerated-failure-time model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. survreg reports AFT coefficients; Weibull PH coefficients require sign and scale conversion.
Stata reference · R reference
streg x z, distribution(weibull) time
survival::survreg(survival::Surv(time, event) ~ x + z, data = data, dist = "weibull")
survival
weibull accelerated-failure-time model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. survreg reports AFT coefficients; Weibull PH coefficients require sign and scale conversion.
Stata reference · R reference
streg x, distribution(loglogistic) strata(group) time
survival::survreg(survival::Surv(time, event) ~ x + factor(group) + strata(group), data = data, dist = "loglogistic")
survival
loglogistic AFT model with group-specific scale
Differs from Stata: factor(group) gives stratum-specific intercepts and strata(group) gives stratum-specific scales, as in Stata streg, strata(). survreg reports AFT coefficients; convert Weibull/exponential coefficients before comparing Stata hazard-ratio output.
Stata reference · R reference
streg x, distribution(lognormal) strata(group) time
survival::survreg(survival::Surv(time, event) ~ x + factor(group) + strata(group), data = data, dist = "lognormal")
survival
lognormal AFT model with group-specific scale
Differs from Stata: factor(group) gives stratum-specific intercepts and strata(group) gives stratum-specific scales, as in Stata streg, strata(). survreg reports AFT coefficients; convert Weibull/exponential coefficients before comparing Stata hazard-ratio output.
Stata reference · R reference
streg x, distribution(weibull) strata(group) time
survival::survreg(survival::Surv(time, event) ~ x + factor(group) + strata(group), data = data, dist = "weibull")
survival
weibull AFT model with group-specific scale
Differs from Stata: factor(group) gives stratum-specific intercepts and strata(group) gives stratum-specific scales, as in Stata streg, strata(). survreg reports AFT coefficients; convert Weibull/exponential coefficients before comparing Stata hazard-ratio output.
Stata reference · R reference
sts graph
plot(survival::survfit(survival::Surv(time, died) ~ 1, data = data))
survival
Kaplan-Meier curve
Stata reference · R reference
sts test group
survival::survdiff(survival::Surv(time, died) ~ group, data = data)
survival
Log-rank test
Stata reference · R reference
sts list
survival::survfit(s ~ 1)
survival
Kaplan-Meier survival curve data
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R returns curve data; confidence transformations and tied-event handling should be specified for comparisons.
Stata reference · R reference
sts list, by(group)
survival::survfit(s ~ data$group)
survival
Group-specific Kaplan-Meier curves
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R returns curve data; confidence transformations and tied-event handling should be specified for comparisons.
Stata reference · R reference
sts list, cumhaz
{ f <- survival::survfit(s ~ 1); data.frame(time = f$time, cumhaz = f$cumhaz) }
survival
Nelson-Aalen cumulative hazard
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R returns curve data; confidence transformations and tied-event handling should be specified for comparisons.
Stata reference · R reference
sts list, failure
{ f <- survival::survfit(s ~ 1); data.frame(time = f$time, failure = 1 - f$surv) }
survival
Cumulative failure probability
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R returns curve data; confidence transformations and tied-event handling should be specified for comparisons.
Stata reference · R reference
sts list, level(95)
survival::survfit(s ~ 1, conf.type = "plain", conf.int = .95)
survival
Kaplan-Meier interval with plain transformation
Fixed workflow; adapt the named data columns explicitly. Explicit R confidence transformation; Stata's displayed default may differ.
Stata reference · R reference
sts list, level(95)
survival::survfit(s ~ 1, conf.type = "log", conf.int = .95)
survival
Kaplan-Meier interval with log transformation
Fixed workflow; adapt the named data columns explicitly. Explicit R confidence transformation; Stata's displayed default may differ.
Stata reference · R reference
sts list, level(95)
survival::survfit(s ~ 1, conf.type = "log-log", conf.int = .95)
survival
Kaplan-Meier interval with log-log transformation
Fixed workflow; adapt the named data columns explicitly. Explicit R confidence transformation; Stata's displayed default may differ.
Stata reference · R reference
sts test group
survival::survdiff(s ~ data$group, rho = 0)
survival
Log-rank comparison of survival curves
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Unstratified two-group log-rank test.
Stata reference · R reference
stset time, failure(died)
survival::Surv(data$time, data$died)
survival
Declare survival-time data
R has no declaration step: Surv(time, died) goes on the left of each model formula.
Stata reference · R reference
stset exit, enter(time entry) failure(event)
survival::Surv(data$entry, data$time, data$event)
survival
Delayed-entry counting-process response
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Supply entry and exit explicitly; multiple spells require one row per risk interval.
Stata reference · R reference
stset time, failure(event)
survival::Surv(data$time, data$event)
survival
Right-censored survival response
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Creates a response object rather than declaring global dataset state.
Stata reference · R reference
stsplit period, at(3 6)
{ Surv <- survival::Surv; survival::survSplit(Surv(time, event) ~ ., data = data, cut = c(3, 6), start = "start", end = "time", event = "event", episode = "period") }
survival
Split risk intervals at fixed cut points
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Returns expanded interval data; the episode variable is an interval index.
Stata reference · R reference
stsum
survival::survfit(survival::Surv(time, died) ~ 1, data = data)
survival
Summary of survival times
Stata reference · R reference
stsum, by(group)
stats::aggregate(cbind(person_time = time, failures = event) ~ group, data = data, FUN = sum)
stats
Person-time and failure counts by group
Fixed workflow; adapt the named data columns explicitly. Subset of stsum output; no survival quantiles are computed.
Stata reference · R reference
sttocc, number(2)
{ cases <- which(data$event == 1); sets <- lapply(seq_along(cases), function(j) { i <- cases[j]; at_risk <- which(data$entry <= data$time[i] & data$time >= data$time[i] & data$id != data$id[i]); controls <- sample(at_risk, min(2L, length(at_risk)), replace = FALSE); out <- data[c(i, controls), ]; out$case <- c(1L, rep(0L, length(controls))); out$set <- j; out$failure_time <- data$time[i]; out }); do.call(rbind, sets) }
base
Sample nested case-control risk sets from a cohort
Fixed workflow; adapt the named data columns explicitly. One-record cohort with no tied failures. Controls are sampled from those at risk for each failure and may recur across sets; tied-failure random ordering and multiple spells need a fuller implementation.
Stata reference · R reference
stvary x z
lapply(split(data, data$id), function(d) vapply(d[c("x", "z")], function(v) c(varies = length(unique(v[!is.na(v)])) > 1, any_missing = anyNA(v)), logical(2)))
base
Check within-subject covariate variation and missingness
Fixed workflow; adapt the named data columns explicitly. Returns per-subject flags rather than Stata's aggregate summary table; ignores sampling weights as stvary does.
Stata reference · R reference

Survey data

Stata R Purpose, qualifications and sources
svy: logit y x
survey::svyglm(y ~ x, design = design, family = quasibinomial())
survey
Survey-weighted logit
Differs from Stata: Match design and missing-data exclusions first; singleton-PSU policy, degrees of freedom and confidence-interval transformations can differ between R and Stata.
Stata reference · R reference
svy: mean x
summarise(design, x = srvyr::survey_mean(x, na.rm = TRUE))
srvyr
Survey-weighted mean
Differs from Stata: Match design and missing-data exclusions first; singleton-PSU policy, degrees of freedom and confidence-interval transformations can differ between R and Stata.
Stata reference · R reference
svy: regress y x
survey::svyglm(y ~ x, design = design)
survey
Survey-weighted regression
Differs from Stata: Match design and missing-data exclusions first; singleton-PSU policy, degrees of freedom and confidence-interval transformations can differ between R and Stata.
Stata reference · R reference
svy: tabulate x
design |> group_by(x) |> summarise(p = srvyr::survey_prop())
srvyr
Survey-weighted proportions
Differs from Stata: Match design and missing-data exclusions first; singleton-PSU policy, degrees of freedom and confidence-interval transformations can differ between R and Stata.
Stata reference · R reference
svy, subpop(rural): mean x
design |> filter(rural == 1) |> summarise(x = srvyr::survey_mean(x, na.rm = TRUE))
srvyr
Subpopulation estimate
Differs from Stata: Filtering a survey design keeps the full design for the variance, as subpop() does. Match design and missing-data exclusions first; singleton-PSU policy, degrees of freedom and confidence-interval transformations can differ between R and Stata.
Stata reference · R reference
svy: mean x, over(g)
design |> group_by(g) |> summarise(x = srvyr::survey_mean(x, na.rm = TRUE))
srvyr
Survey-weighted means by group
Differs from Stata: Match design and missing-data exclusions first; singleton-PSU policy, degrees of freedom and confidence-interval transformations can differ between R and Stata.
Stata reference · R reference
svy: proportion x
design |> group_by(x) |> summarise(p = srvyr::survey_prop(vartype = "ci"))
srvyr
Survey-weighted proportions with intervals
Differs from Stata: Match design and missing-data exclusions first; singleton-PSU policy, degrees of freedom and confidence-interval transformations can differ between R and Stata.
Stata reference · R reference
svydescribe
summary(design)
base
Describe the survey design
Stata reference · R reference
svyset psu [pweight = wt], strata(stratum)
design <- srvyr::as_survey_design(data, ids = psu, strata = stratum, weights = wt)
srvyr
Declare a survey design
Differs from Stata: Match design and missing-data exclusions first; singleton-PSU policy, degrees of freedom and confidence-interval transformations can differ between R and Stata.
Stata reference · R reference

Graphs

Stata R Purpose, qualifications and sources
binscatter y x
binsreg::binsreg(y, x, data = data)
binsreg
Binned scatter plot
Differs from Stata: statar::stat_binmean() adds binned means to a ggplot: ggplot(data, aes(x, y)) + statar::stat_binmean(n = 20). binsreg() defaults to data-driven bin selection and inference; binscatter defaults to fixed quantile bins and an OLS fit. Match bins and fit settings explicitly.
Stata reference · R reference
coefplot
modelsummary::modelplot(fit)
modelsummary
Coefficient plot
Stata reference · R reference
dotplot y, over(group)
ggplot2::ggplot(data, ggplot2::aes(group, y)) + ggplot2::geom_point(position = ggplot2::position_jitter(width = 0.15, height = 0))
ggplot2
Show individual observations by category
Differs from Stata: This uses horizontally jittered observations rather than Stata dot-stacking rules.
Stata reference · R reference
graph bar (count), over(x)
ggplot(data, aes(x)) + geom_bar()
ggplot2
Bar chart of counts
Stata reference · R reference
graph bar (mean) y, over(group)
ggplot(data, aes(group, y)) + stat_summary(fun = mean, geom = "bar")
ggplot2
Bar chart of group means
Stata reference · R reference
graph box y, over(group)
ggplot(data, aes(group, y)) + geom_boxplot()
ggplot2
Box plot
Differs from Stata: ggplot2 boxplot hinges use R quantile rules; Stata uses Stata percentiles, which may differ in small samples and with ties.
Stata reference · R reference
graph export figure.png
ggsave("figure.png")
ggplot2
Save the last graph
Stata reference · R reference
graph pie, over(group)
ggplot(data, aes(x = "", fill = group)) + geom_bar() + coord_polar(theta = "y")
ggplot2
Pie chart
Stata reference · R reference
graph combine g1.gph g2.gph
patchwork::wrap_plots(p1, p2)
patchwork
Combine plots
With patchwork attached, p1 + p2 does the same.
Stata reference · R reference
graph dot (mean) y, over(group)
ggplot(data, aes(y, group)) + stat_summary(fun = mean, geom = "point")
ggplot2
Dot chart
Stata reference · R reference
graph hbar (mean) y, over(group)
ggplot(data, aes(group, y)) + stat_summary(fun = mean, geom = "bar") + coord_flip()
ggplot2
Horizontal bar chart
Stata reference · R reference
graph hbox y, over(group)
ggplot(data, aes(y, group)) + geom_boxplot()
ggplot2
Horizontal box plot
Differs from Stata: ggplot2 boxplot hinges use R quantile rules; Stata uses Stata percentiles, which may differ in small samples and with ties.
Stata reference · R reference
graph matrix x1 x2 x3
pairs(select(data, x1, x2, x3))
graphics
Scatter-plot matrix
GGally::ggpairs() draws a ggplot2 version.
Stata reference · R reference
graph save fig.gph
saveRDS(p, "fig.rds")
base
Save a plot to edit later
Stata reference · R reference
graph bar (count), over(group)
ggplot2::ggplot(data, ggplot2::aes(group)) + ggplot2::geom_bar()
ggplot2
Plot group frequencies
Differs from Stata: Reproduces the displayed count, percent or summary layer, rather than Stata graph display defaults. Match category order and missingness; ggplot themes, axis scales and bar annotations follow R conventions.
Stata reference · R reference
graph bar (mean) y, over(group)
ggplot2::ggplot(data, ggplot2::aes(group, y)) + ggplot2::stat_summary(fun = mean, geom = "col")
ggplot2
Plot group means as bars
Differs from Stata: Reproduces the displayed count, percent or summary layer, rather than Stata graph display defaults. Match category order and missingness; ggplot themes, axis scales and bar annotations follow R conventions.
Stata reference · R reference
graph bar (mean) y, over(group) blabel(bar)
{ plot_data <- aggregate(y ~ group, data, mean); ggplot2::ggplot(plot_data, ggplot2::aes(group, y)) + ggplot2::geom_col() + ggplot2::geom_text(ggplot2::aes(label = round(y, 1)), vjust = -0.3) }
ggplot2
Label summary bars with their values
Differs from Stata: Reproduces the displayed count, percent or summary layer, rather than Stata graph display defaults. Match category order and missingness; ggplot themes, axis scales and bar annotations follow R conventions.
Stata reference · R reference
graph bar (median) y, over(group)
ggplot2::ggplot(data, ggplot2::aes(group, y)) + ggplot2::stat_summary(fun = median, geom = "col")
ggplot2
Plot group medians as bars
Differs from Stata: Reproduces the displayed count, percent or summary layer, rather than Stata graph display defaults. Match category order and missingness; ggplot themes, axis scales and bar annotations follow R conventions.
Stata reference · R reference
graph bar (percent), over(group)
{ counts <- as.data.frame(table(data$group)); ggplot2::ggplot(counts, ggplot2::aes(Var1, Freq / sum(Freq) * 100)) + ggplot2::geom_col() }
ggplot2
Plot group percentages
Differs from Stata: Reproduces the displayed count, percent or summary layer, rather than Stata graph display defaults. Match category order and missingness; ggplot themes, axis scales and bar annotations follow R conventions.
Stata reference · R reference
graph bar (sum) y, over(group)
ggplot2::ggplot(data, ggplot2::aes(group, y)) + ggplot2::stat_summary(fun = sum, geom = "col")
ggplot2
Plot group totals as bars
Differs from Stata: Reproduces the displayed count, percent or summary layer, rather than Stata graph display defaults. Match category order and missingness; ggplot themes, axis scales and bar annotations follow R conventions.
Stata reference · R reference
graph box y, over(group)
ggplot2::ggplot(data, ggplot2::aes(group, y)) + ggplot2::geom_boxplot()
ggplot2
Compare distributions with box plots
Differs from Stata: Box-plot hinges and whisker defaults should be checked when numerical parity is required.
Stata reference · R reference
graph box y, over(group) nooutsides
ggplot2::ggplot(data, ggplot2::aes(group, y)) + ggplot2::geom_boxplot(outlier.shape = NA)
ggplot2
Hide box-plot outlier markers
Differs from Stata: Box-plot hinges and whisker defaults should be checked when numerical parity is required.
Stata reference · R reference
graph dot (mean) y, over(group)
ggplot2::ggplot(data, ggplot2::aes(y, group)) + ggplot2::stat_summary(fun = mean, geom = "point")
ggplot2
Plot group means as dots
Differs from Stata: Reproduces the displayed count, percent or summary layer, rather than Stata graph display defaults. Match category order and missingness; ggplot themes, axis scales and bar annotations follow R conventions.
Stata reference · R reference
graph hbox y, over(group)
ggplot2::ggplot(data, ggplot2::aes(y, group)) + ggplot2::geom_boxplot()
ggplot2
Draw horizontal box plots
Differs from Stata: Box-plot hinges and whisker defaults should be checked when numerical parity is required.
Stata reference · R reference
heatplot z y x
ggplot2::ggplot(data, ggplot2::aes(x, y, z = z)) + ggplot2::stat_summary_2d(fun = mean)
ggplot2
Heat map of the mean of z over binned x and y
Differs from Stata: Community command. Both average z within cells, but bin counts and boundaries differ; set bins explicitly (bins() in Stata, bins = in R) when comparing. Colour ramps follow each program's defaults.
Stata reference · R reference
heatplot z i.y i.x
ggplot2::ggplot(stats::aggregate(z ~ x + y, data = data, FUN = mean), ggplot2::aes(factor(x), factor(y), fill = z)) + ggplot2::geom_tile()
ggplot2
Heat map of the mean of z over categories of x and y
Differs from Stata: Community command. One tile per observed x-y combination, filled with the mean of z; empty combinations are left blank in both.
Stata reference · R reference
histogram x
ggplot(data, aes(x)) + geom_histogram()
ggplot2
Histogram
Differs from Stata: geom_histogram() defaults to counts and 30 bins; Stata histogram defaults to density with a different bin rule. Specify breaks/binwidth and the y statistic.
Stata reference · R reference
histogram y, by(group)
ggplot2::ggplot(data, ggplot2::aes(y)) + ggplot2::geom_histogram(bins = 10) + ggplot2::facet_wrap(~group)
ggplot2
Compare histograms across groups
Differs from Stata: Set boundaries and interval closure explicitly when matching Stata bin counts.
Stata reference · R reference
histogram y, density
ggplot2::ggplot(data, ggplot2::aes(y, ggplot2::after_stat(density))) + ggplot2::geom_histogram(bins = 10)
ggplot2
Histogram on the density scale
Differs from Stata: Set boundaries and interval closure explicitly when matching Stata bin counts.
Stata reference · R reference
histogram y, frequency
ggplot2::ggplot(data, ggplot2::aes(y)) + ggplot2::geom_histogram(bins = 10)
ggplot2
Histogram on the frequency scale
Differs from Stata: Set boundaries and interval closure explicitly when matching Stata bin counts.
Stata reference · R reference
histogram y, percent
ggplot2::ggplot(data, ggplot2::aes(y, ggplot2::after_stat(count / sum(count) * 100))) + ggplot2::geom_histogram(bins = 10)
ggplot2
Histogram on the percentage scale
Differs from Stata: Set boundaries and interval closure explicitly when matching Stata bin counts.
Stata reference · R reference
histogram y, width(2) start(0)
ggplot2::ggplot(data, ggplot2::aes(y)) + ggplot2::geom_histogram(binwidth = 2, boundary = 0)
ggplot2
Choose histogram width and boundary
Differs from Stata: Set boundaries and interval closure explicitly when matching Stata bin counts.
Stata reference · R reference
histogram z, discrete
ggplot2::ggplot(data, ggplot2::aes(z)) + ggplot2::geom_histogram(binwidth = 1, boundary = 0.5)
ggplot2
Histogram for integer-valued observations
Differs from Stata: Set boundaries and interval closure explicitly when matching Stata bin counts.
Stata reference · R reference
kdensity x
ggplot(data, aes(x)) + geom_density()
ggplot2
Density plot
Differs from Stata: Default kernel-density bandwidth rules differ; specify kernel, bandwidth and evaluation range before comparing curves.
Stata reference · R reference
kdensity y
ggplot2::ggplot(data, ggplot2::aes(y)) + ggplot2::geom_density()
ggplot2
Plot a kernel density estimate
Differs from Stata: R and Stata bandwidth rules and local smoothing algorithms can differ; this is a graphical alternative, not an exact numerical replication.
Stata reference · R reference
kdensity y if group == "A"
ggplot2::ggplot(subset(data, group == "A"), ggplot2::aes(y)) + ggplot2::geom_density()
ggplot2
Estimate a density for a subgroup
Differs from Stata: R and Stata bandwidth rules and local smoothing algorithms can differ; this is a graphical alternative, not an exact numerical replication.
Stata reference · R reference
kdensity y, bwidth(1)
ggplot2::ggplot(data, ggplot2::aes(y)) + ggplot2::geom_density(bw = 1)
ggplot2
Specify a kernel bandwidth
Differs from Stata: R and Stata bandwidth rules and local smoothing algorithms can differ; this is a graphical alternative, not an exact numerical replication.
Stata reference · R reference
kdensity y, kernel(gaussian)
ggplot2::ggplot(data, ggplot2::aes(y)) + ggplot2::geom_density(kernel = "gaussian")
ggplot2
Use a Gaussian density kernel
Differs from Stata: R and Stata bandwidth rules and local smoothing algorithms can differ; this is a graphical alternative, not an exact numerical replication.
Stata reference · R reference
line y x
ggplot(data, aes(x, y)) + geom_line()
ggplot2
Line plot
Differs from Stata: geom_line() sorts by x within groups; Stata line/connected uses observation order without the sort option.
Stata reference · R reference
line y x, sort
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_line()
ggplot2
Line plot sorted by the horizontal variable
Differs from Stata: Maps the stated axes and layer; line sorts by x in ggplot while Stata uses sort here. Plot themes, axis expansion, missing-point warnings and facet scales follow R defaults.
Stata reference · R reference
line y x, sort by(group)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_line() + ggplot2::facet_wrap(~group)
ggplot2
Draw line plots in separate group panels
Differs from Stata: Maps the stated axes and layer; line sorts by x in ggplot while Stata uses sort here. Plot themes, axis expansion, missing-point warnings and facet scales follow R defaults.
Stata reference · R reference
line y x, sort lcolor(red)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_line(colour = "red")
ggplot2
Set a line colour
Differs from Stata: Maps the stated axes and layer; line sorts by x in ggplot while Stata uses sort here. Plot themes, axis expansion, missing-point warnings and facet scales follow R defaults.
Stata reference · R reference
lowess y x
ggplot(data, aes(x, y)) + geom_point() + geom_smooth(method = "loess")
ggplot2
Smoothed scatter plot
Differs from Stata: LOESS local polynomials differ from Stata LOWESS smoothing, robustness iterations and bandwidth defaults; the fitted curves need not coincide.
Stata reference · R reference
lowess y x, bwidth(0.5)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_smooth(method = "loess", formula = y ~ x, span = 0.5, se = FALSE)
ggplot2
Draw a local regression smooth
Differs from Stata: R and Stata bandwidth rules and local smoothing algorithms can differ; this is a graphical alternative, not an exact numerical replication.
Stata reference · R reference
pchi y, df(2)
graphics::plot(ppoints(length(data$y)), pchisq(sort(data$y), df = 2))
graphics
Compare empirical and chi-squared probabilities
Differs from Stata: A diagnostic plotting workflow; plotting-position and standardization defaults can differ from Stata.
Stata reference · R reference
pnorm y
graphics::plot(ppoints(length(data$y)), pnorm(as.numeric(scale(sort(data$y)))), xlab = "Empirical", ylab = "Normal")
graphics
Assess a standardized normal P-P relationship
Differs from Stata: A diagnostic plotting workflow; plotting-position and standardization defaults can differ from Stata.
Stata reference · R reference
qchi y, df(2)
graphics::plot(qchisq(ppoints(length(data$y)), df = 2), sort(data$y))
graphics
Compare sample quantiles with chi-squared quantiles
Differs from Stata: A diagnostic plotting workflow; plotting-position and standardization defaults can differ from Stata.
Stata reference · R reference
qnorm x
ggplot(data, aes(sample = x)) + geom_qq() + geom_qq_line()
ggplot2
Normal quantile plot
Differs from Stata: geom_qq() defaults to theoretical standard-normal quantiles; qnorm scales the normal axis by the sample mean and SD. Match axis scaling to compare points.
Stata reference · R reference
qqplot y x
stats::qqplot(data$x, data$y)
stats
Compare two empirical distributions with a Q-Q plot
Differs from Stata: A diagnostic plotting workflow; plotting-position and standardization defaults can differ from Stata.
Stata reference · R reference
quantile y
graphics::plot(ppoints(sum(!is.na(data$y))), sort(data$y), xlab = "Fraction", ylab = "y")
graphics
Plot ordered data against cumulative fractions
Differs from Stata: A diagnostic plotting workflow; plotting-position and standardization defaults can differ from Stata.
Stata reference · R reference
scatter y x
ggplot(data, aes(x, y)) + geom_point()
ggplot2
Scatter plot
Stata reference · R reference
scatter y x, mlabel(name)
ggplot(data, aes(x, y, label = name)) + geom_point() + geom_text()
ggplot2
Label the points
Stata reference · R reference
scatter y x, xline(0)
ggplot(data, aes(x, y)) + geom_point() + geom_vline(xintercept = 0)
ggplot2
Add a reference line
geom_hline(yintercept = 0) is yline().
Stata reference · R reference
scatter y x
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point()
ggplot2
Scatter plot with ggplot2
Differs from Stata: Maps the stated axes and layer; line sorts by x in ggplot while Stata uses sort here. Plot themes, axis expansion, missing-point warnings and facet scales follow R defaults.
Stata reference · R reference
scatter y x, aspectratio(1)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point() + ggplot2::theme(aspect.ratio = 1)
ggplot2
Make the plotting panel square
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, by(group)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point() + ggplot2::facet_wrap(~group)
ggplot2
Separate scatter plots by group
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, jitter(2)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_jitter(width = 0.2, height = 0.2)
ggplot2
Jitter overlapping observations
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, legend(off)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point(ggplot2::aes(colour = group)) + ggplot2::theme(legend.position = "none")
ggplot2
Hide a graph legend
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, mcolor(red)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point(colour = "red")
ggplot2
Set the marker colour
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, mlabel(label)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_text(ggplot2::aes(label = label))
ggplot2
Label each point with a variable
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, msize(large)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point(size = 3)
ggplot2
Increase marker size
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, msymbol(Oh)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point(shape = 1)
ggplot2
Draw hollow circular markers
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, note("Source: survey")
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point() + ggplot2::labs(caption = "Source: survey")
ggplot2
Add a source note to a graph
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, scheme(s2mono)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point() + ggplot2::theme_bw()
ggplot2
Use a monochrome-friendly theme
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, subtitle("Wave 1")
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point() + ggplot2::labs(subtitle = "Wave 1")
ggplot2
Add a graph subtitle
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, title("Sample")
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point() + ggplot2::labs(title = "Sample")
ggplot2
Add a graph title
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, xlabel(0(5)30)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point() + ggplot2::scale_x_continuous(breaks = seq(0, 30, 5))
ggplot2
Choose horizontal axis breaks
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, xline(10)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point() + ggplot2::geom_vline(xintercept = 10)
ggplot2
Add a vertical reference line
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, xscale(log)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point() + ggplot2::scale_x_log10()
ggplot2
Use a logarithmic predictor axis
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, xtitle("Age")
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point() + ggplot2::labs(x = "Age")
ggplot2
Label the horizontal axis
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, ylabel(0(5)20)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point() + ggplot2::scale_y_continuous(breaks = seq(0, 20, 5))
ggplot2
Choose vertical axis breaks
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, yline(5)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point() + ggplot2::geom_hline(yintercept = 5)
ggplot2
Add a horizontal reference line
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, yscale(log)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point() + ggplot2::scale_y_log10()
ggplot2
Use a logarithmic response axis
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
scatter y x, ytitle("Income")
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point() + ggplot2::labs(y = "Income")
ggplot2
Label the vertical axis
Differs from Stata: The R example implements the graphical intent; size, jitter and theme scales are not numerically identical to Stata.
Stata reference · R reference
serrbar y se x
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_errorbar(ggplot2::aes(ymin = y - se, ymax = y + se)) + ggplot2::geom_point()
ggplot2
Plot supplied estimates and standard errors
Differs from Stata: Here se is a supplied standard-error variable; Stata serrbar defaults to one standard error. Rename the variable to suit your data.
Stata reference · R reference
set scheme s1mono
theme_set(theme_bw())
ggplot2
Change the look of every graph
Stata reference · R reference
spikeplot z
{ counts <- as.data.frame(table(data$z)); graphics::plot(as.numeric(as.character(counts$Var1)), counts$Freq, type = "h") }
graphics
Plot spikes for the frequencies of distinct values
Differs from Stata: Draws one spike for each observed value with its count. Axis ticks, spike widths, handling of missing values and graphics device styling differ from Stata spikeplot.
Stata reference · R reference
symplot y
{ values <- sort(data$y); half <- length(values) %/% 2L; centre <- median(values); graphics::plot(centre - rev(head(values, half)), tail(values, half) - centre) }
graphics
Check symmetry around the sample median
Differs from Stata: A diagnostic plotting workflow; plotting-position and standardization defaults can differ from Stata.
Stata reference · R reference
twoway (scatter y x) (lfit y x)
ggplot(data, aes(x, y)) + geom_point() + geom_smooth(method = "lm")
ggplot2
Scatter plot with a fitted line
Differs from Stata: geom_smooth(method = "lm") adds a confidence band by default; lfit has no band. Use se = FALSE for the same plotted layer.
Stata reference · R reference
twoway area y x
ggplot(data, aes(x, y)) + geom_area()
ggplot2
Area plot
Stata reference · R reference
twoway connected y x
ggplot(data, aes(x, y)) + geom_line() + geom_point()
ggplot2
Connected line plot
Differs from Stata: geom_line() sorts by x within groups; Stata line/connected uses observation order without the sort option.
Stata reference · R reference
twoway rarea hi lo x
ggplot(data, aes(x, ymin = lo, ymax = hi)) + geom_ribbon()
ggplot2
Shaded range
Stata reference · R reference
twoway rcap hi lo x
ggplot(data, aes(x, ymin = lo, ymax = hi)) + geom_errorbar()
ggplot2
Range plot with capped spikes
Stata reference · R reference
twoway (scatter y x if g == 1) (scatter y x if g == 2)
ggplot(data, aes(x, y, colour = factor(g))) + geom_point()
ggplot2
Colour points by group
Stata reference · R reference
twoway lfitci y x
ggplot(data, aes(x, y)) + geom_smooth(method = "lm")
ggplot2
Linear fit with a confidence band
Stata reference · R reference
twoway qfit y x
ggplot(data, aes(x, y)) + geom_smooth(method = "lm", formula = y ~ poly(x, 2), se = FALSE)
ggplot2
Quadratic fit
Stata reference · R reference
twoway scatter y x, by(group)
ggplot(data, aes(x, y)) + geom_point() + facet_wrap(~group)
ggplot2
One panel per group
Stata reference · R reference
twoway (scatter y x) (lfit y x)
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point() + ggplot2::geom_smooth(method = "lm", formula = y ~ x, se = FALSE)
ggplot2
Overlay a linear fitted relationship
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
twoway area y x, sort
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_area()
ggplot2
Fill the area beneath a line
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
twoway connected y x, sort
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_line() + ggplot2::geom_point()
ggplot2
Connect points in horizontal order
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
twoway contour y x z
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_contour(ggplot2::aes(z = z))
ggplot2
Draw contour lines on a regular grid
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
twoway dropline y x
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_segment(ggplot2::aes(xend = x, yend = 0)) + ggplot2::geom_point()
ggplot2
Draw points with drop lines
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
twoway lfitci y x
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_smooth(method = "lm", formula = y ~ x, level = 0.95)
ggplot2
Plot a linear fit with confidence limits
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
twoway pcarrow y x hi z
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_segment(ggplot2::aes(xend = z, yend = hi), arrow = grid::arrow())
ggplot2
Draw arrows between paired coordinates
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
twoway pcspike y x hi z
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_segment(ggplot2::aes(xend = z, yend = hi))
ggplot2
Connect paired coordinate endpoints
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
twoway qfitci y x
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_smooth(method = "lm", formula = y ~ poly(x, 2), level = 0.95)
ggplot2
Plot a quadratic fit with confidence limits
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
twoway rarea lo hi x, sort
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_ribbon(ggplot2::aes(ymin = lo, ymax = hi))
ggplot2
Draw a shaded uncertainty band
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
twoway rbar lo hi x
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_rect(ggplot2::aes(xmin = x - 0.4, xmax = x + 0.4, ymin = lo, ymax = hi))
ggplot2
Draw bars spanning lower and upper values
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
twoway rcap lo hi x
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_errorbar(ggplot2::aes(ymin = lo, ymax = hi))
ggplot2
Draw capped uncertainty intervals
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
twoway rscatter lo hi x
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point(ggplot2::aes(y = lo)) + ggplot2::geom_point(ggplot2::aes(y = hi))
ggplot2
Plot both endpoints of a range
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
twoway rspike lo hi x
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_linerange(ggplot2::aes(ymin = lo, ymax = hi))
ggplot2
Show ranges with vertical lines
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
twoway scatter y x
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_point()
ggplot2
Draw a two-variable scatter plot
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
twoway spike y x
ggplot2::ggplot(data, ggplot2::aes(x, y)) + ggplot2::geom_segment(ggplot2::aes(xend = x, yend = 0))
ggplot2
Draw vertical spikes from zero
Differs from Stata: Graphical workflow; plotting defaults can differ.
Stata reference · R reference
vioplot y, over(group)
ggplot(data, aes(group, y)) + geom_violin()
ggplot2
Violin plot
Stata reference · R reference

Programming utilities

Stata R Purpose, qualifications and sources
about
utils::sessionInfo()
utils
Inspect R version and platform information
Reports R session metadata; Stata license and serial information have no R counterpart.
Stata reference · R reference
adopath
.libPaths()
base
Inspect the package library search path
R package libraries replace ado search directories; this only reads the current path.
Stata reference · R reference
program define addtwo
args a b
display `a'+`b'
end
addtwo <- function(a,b) a+b
base
Receive two positional arguments in a function
R function arguments replace positional Stata macros; this is a fixed program example.
Stata reference · R reference
forvalues i=1/4 {
    if `i'==2 continue
    display `i'
}
out <- integer(); for (i in 1:4) { if(i==2) next; out <- c(out,i) }
base
Skip the rest of one loop iteration
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
forvalues i=1/4 {
    if `i'==3 continue, break
    display `i'
}
out <- integer(); for (i in 1:4) { if(i==3) break; out <- c(out,i) }
base
Exit a loop early
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
creturn list
list(version=R.version.string,platform=R.version$platform,working_directory=getwd(),machine=.Machine)
base
Inspect R version, platform, paths and numeric limits
Returns R's own settings and constants, not Stata's c-class values.
Stata reference · R reference
dataex id x in 1/3
example <- data[1:3,c('id','x')]; text <- utils::capture.output(dput(example))
base
Create reproducible R code for a small data example
dput emits R reconstruction code, not Stata input code or forum markup. Share only data already approved for disclosure.
Stata reference · R reference
error 198
fail <- function() stop('Invalid input',call.=FALSE)
base
Raise a clear error from a function
R conditions replace numeric Stata return codes; the check catches the deliberately raised error.
Stata reference · R reference
program define positive
args x
if `x'<=0 exit
display `x'
end
positive <- function(x) { if(x<=0) return(invisible(NULL)); x }
base
Return early from a function
Function-level return only; quitting the R process would terminate the user's session.
Stata reference · R reference
ftools, version
list(version=as.character(utils::packageVersion('dplyr')),available=requireNamespace('dplyr',quietly=TRUE))
utils
Inspect the R data-manipulation package version and availability
Reports the chosen R workflow dependency, dplyr; it does not inspect or compile a Stata Mata library.
Stata reference · R reference
gettoken first rest : text
parts <- strsplit(text,' +')[[1]]; first <- parts[1]; rest <- paste(parts[-1],collapse=' ')
base
Split the first simple token from the remaining text
Differs from Stata: Simple unquoted whitespace tokens only; Stata quoting and bind rules are not reproduced.
Stata reference · R reference
include helper.do
sys.source(path,envir=environment())
base
Execute helper code in the current evaluation environment
Only sources the controlled temporary R helper here; R syntax replaces the Stata do-file.
Stata reference · R reference
mark touse if g == 2
data$touse <- as.integer(!is.na(data$g) & data$g==2)
base
Create an inclusion marker from a condition
Stata reference · R reference
markin if g == 2
selected <- which(data$g==2); interval <- range(selected)
base
Find the row range enclosing a selected sample
Returns enclosing row endpoints only; selection can contain gaps and is not replaced by that interval.
Stata reference · R reference
markout touse x y
data$touse <- as.integer(data$touse==1 & stats::complete.cases(data[c('x','y')]))
base
Clear an inclusion marker when variables are incomplete
Stata reference · R reference
syntax varlist
marksample touse
touse <- stats::complete.cases(data[vars])
base
Mark complete rows over supplied column names
R receives column names explicitly; no Stata syntax parser state or if/in qualifiers are read.
Stata reference · R reference
matlist X, format(%9.2f)
format(X,nsmall=2,trim=TRUE)
base
Format a numeric matrix for display
Differs from Stata: Returns a character matrix; R does not duplicate Stata's borders/equation headers.
Stata reference · R reference
matname X first second, columns(1..2)
colnames(X) <- c('first','second')
base
Name matrix columns
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
mkmat x y, matrix(X)
X <- as.matrix(data[c('x','y')])
base
Create a matrix from selected numeric variables
Differs from Stata: X is the fixed matrix object name; R row names need not match Stata r1, r2 labels.
Stata reference · R reference
mkmat x y, matrix(X) nomissing
X <- as.matrix(data[stats::complete.cases(data[c('x','y')]),c('x','y')])
base
Create a matrix after listwise missing exclusion
Stata reference · R reference
numlist "1(2)9"
values <- seq(1,9,by=2)
base
Expand a numeric list with a fixed step
Constructs this list directly; it does not parse arbitrary Stata numlist strings.
Stata reference · R reference
numlist "5/1"
values <- seq(5,1,by=-1)
base
Expand a decreasing consecutive numeric list
Direct R sequence workflow for the displayed Stata list.
Stata reference · R reference
post handle (1) (2.5)
results <- rbind(results,data.frame(id=1L,value=2.5))
base
Append one result observation
Appends to the R accumulator; a separate save writes the final file.
Stata reference · R reference
postclose handle
saveRDS(results,path)
base
Persist an accumulated result table
Finalizes the R accumulator as RDS rather than closing a Stata postfile handle.
Stata reference · R reference
postfile handle id value using results.dta, replace
results <- data.frame(id=integer(),value=double())
base
Initialize a typed result accumulator
R accumulator workflow: append rows, then save separately; no disk handle is opened yet.
Stata reference · R reference
query output
options()[c('width','digits','scipen')]
base
Inspect current R output settings
Read-only R settings query; these are R-specific options rather than Stata parameter names.
Stata reference · R reference
require ftools
stopifnot(requireNamespace('dplyr',quietly=TRUE))
base
Require an installed R workflow dependency
Checks the R counterpart dependency dplyr; no package is installed and Stata package names do not translate automatically.
Stata reference · R reference
require ftools >= 2.48.0
stopifnot(requireNamespace('dplyr',quietly=TRUE),utils::packageVersion('dplyr') >= '1.1.0')
base
Require a minimum version of an R workflow dependency
The R counterpart has its own version requirement; 1.1.0 supports the .by and relationship features used in these examples.
Stata reference · R reference
sleep 1
Sys.sleep(0.001)
base
Pause execution using milliseconds converted to seconds
R Sys.sleep takes seconds; no machine-speed timing assertion is made.
Stata reference · R reference
svmat X, names(col)
data <- as.data.frame(X)
base
Convert matrix columns to named variables
Differs from Stata: Creates a new table; merging with an existing dataset requires an explicit row/key alignment.
Stata reference · R reference
syntax varname(numeric) [, Scale(real 1)]
scaled_sum <- function(data,var,scale=1) { stopifnot(length(var)==1L,var %in% names(data),is.numeric(data[[var]]),is.numeric(scale),length(scale)==1L); sum(data[[var]],na.rm=TRUE)*scale }
base
Validate a numeric column argument and an optional scalar
Uses R formals and explicit checks; it does not parse Stata's command grammar.
Stata reference · R reference
sysdir list
list(home=R.home(),library=R.home('library'),temporary=tempdir())
base
Inspect R installation and temporary directories
Shows R directories; Stata BASE/PLUS/PERSONAL directories have no one-to-one mapping.
Stata reference · R reference
tempfile cache
path <- tempfile(fileext='.rds')
base
Reserve a unique temporary path
Differs from Stata: tempfile() reserves a name without creating a file; R does not guarantee Stata-style cleanup of each named file when a function exits.
Stata reference · R reference
tempname total
scalar `total' = 10
local({ total <- 10; total*2 })
base
Use a temporary scalar inside local scope
Lexical scope supplies isolation rather than a unique Stata temporary object name.
Stata reference · R reference
tempvar squared
generate `squared' = x^2
local({ squared <- data$x^2; sum(squared,na.rm=TRUE) })
base
Compute with a temporary vector in a local scope
R local scope avoids adding a temporary dataset column; no Stata macro name is generated.
Stata reference · R reference
tokenize "alpha beta" gamma
tokens <- scan(text='"alpha beta" gamma',what=character(),quiet=TRUE)
base
Tokenize a quoted phrase and a word
Differs from Stata: Demonstrates basic double-quoted whitespace tokens; Stata compound quoting has no automatic equivalent.
Stata reference · R reference
tokenize alpha beta gamma
tokens <- strsplit('alpha beta gamma',' +')[[1]]
base
Split simple whitespace-separated tokens
Differs from Stata: R returns a character vector instead of positional local macros; quoted-token parsing differs.
Stata reference · R reference
unab vars : income
vars <- names(data)[pmatch('income',names(data),duplicates.ok=FALSE)]; stopifnot(!anyNA(vars))
base
Resolve an unambiguous abbreviated column name
R partial matching must be requested explicitly; exact matches take precedence.
Stata reference · R reference
unab vars : x*
vars <- grep('^x',names(data),value=TRUE)
base
Expand a column-name prefix wildcard
Handles the displayed simple prefix wildcard; this is not a complete Stata varlist parser.
Stata reference · R reference
unabcmd gen
full <- match.arg('mea',c('mean','median','sum'))
base
Resolve a unique abbreviation among known R choices
Illustrates explicit R-choice matching, not translation of Stata command abbreviations; Stata gen corresponds to generate.
Stata reference · R reference
viewsource mean.ado
body(base::mean.default)
base
Inspect the body of a named R function
Reads an R function body rather than opening a Stata ado source editor.
Stata reference · R reference

Data management

Stata R Purpose, qualifications and sources
append using other.dta
data <- dplyr::bind_rows(data,other)
dplyr
Append tables allowing different column sets
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
append using other.dta, keep(x)
data <- dplyr::bind_rows(data,other['x'])
dplyr
Append only selected columns from the using table
Stata reference · R reference
append using second.dta third.dta, generate(source)
data <- dplyr::bind_rows(list('0'=data,'1'=second,'2'=third),.id='source'); data$source <- as.integer(data$source)
dplyr
Record origin while appending several datasets
Stata reference · R reference
assertnested id, within(g)
stopifnot(all(vapply(split(data$g,data$id),function(z) length(unique(z))==1L,logical(1))))
base
Assert a group attribute is constant for each identifier
Stata reference · R reference
assertnested region district
stopifnot(all(vapply(split(data$region,data$district),function(z) length(unique(z))==1L,logical(1))))
base
Assert that districts belong to one region
Stata reference · R reference
cf x using other.dta, verbose
which(data$x != other$x | xor(is.na(data$x),is.na(other$x)))
base
Locate differing rows in a selected column
Workflow inspects x only; compare each column for the complete verbose report.
Stata reference · R reference
cf x y using other.dta
stopifnot(identical(unname(as.matrix(data[c('x','y')])),unname(as.matrix(other[c('x','y')]))))
base
Assert selected dataset values match
Differs from Stata: Compares the supplied in-memory other table in row order; ignores metadata as cf does.
Stata reference · R reference
clonevar copy = x
data$copy <- data$x
base
Copy a column and its attributes
Stata reference · R reference
codebook x, compact
c(nonmissing=sum(!is.na(data$x)),unique=length(unique(data$x[!is.na(data$x)])),min=min(data$x,na.rm=TRUE),max=max(data$x,na.rm=TRUE))
base
Describe observed count, distinct count and range
Differs from Stata: Numeric codebook subset; does not reproduce Stata's variable-label and format report.
Stata reference · R reference
compare x y
c(less=sum(data$x<data$y,na.rm=TRUE),equal=sum(data$x==data$y,na.rm=TRUE),greater=sum(data$x>data$y,na.rm=TRUE),x_missing_only=sum(is.na(data$x)&!is.na(data$y)),both_missing=sum(is.na(data$x)&is.na(data$y)))
base
Compare value ordering and missingness
Differs from Stata: Produces the principal comparison counts; not Stata's formatted difference summary.
Stata reference · R reference
compare x y if g == 1
with(subset(data,g==1),table(sign(x-y),useNA='ifany'))
base
Compare ordering inside a subset
Differs from Stata: Returns ordering counts only; use a separate summary for difference magnitudes.
Stata reference · R reference
compress x
stopifnot(all(is.na(data$x) | (data$x==trunc(data$x) & abs(data$x)<=.Machine$integer.max))); data$x <- as.integer(data$x)
base
Reduce safe whole-number storage to R integers
Manual whole-number optimization only. R has no Stata byte/int storage classes or general compress equivalent.
Stata reference · R reference
count if !missing(x, y)
sum(stats::complete.cases(data[c('x','y')]))
base
Count rows complete on selected columns
Stata reference · R reference
count if missing(x)
sum(is.na(data$x))
base
Count missing values
Stata reference · R reference
count if x > 2 & x < .
sum(data$x > 2,na.rm=TRUE)
base
Count observed values above a threshold
Stata reference · R reference
count in 2/5
nrow(data[2:5,,drop=FALSE])
base
Count a row interval
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
cross using other.dta
data <- dplyr::cross_join(data,other)
dplyr
Form the Cartesian product of two datasets
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
cumul x, generate(c)
data$c <- dplyr::row_number(data$x) / sum(!is.na(data$x))
dplyr
Create the empirical cumulative distribution of a variable
Differs from Stata: Missing values stay missing and are excluded from the denominator. By default Stata gives tied values distinct cumulatives in an arbitrary order; R breaks ties by row order. Weights and by() need an explicit grouped or weighted version.
Stata reference · R reference
cumul x, generate(c) equal
data$c <- dplyr::cume_dist(data$x)
dplyr
Cumulative distribution with equal values for ties
Tied values share the largest cumulative proportion, as ecdf(x)(x) does; missing values stay missing.
Stata reference · R reference
datasignature confirm
stopifnot(identical(signature,serialize(data,NULL,version=2)))
base
Assert data match a stored R signature
R-specific byte comparison; not interoperable with Stata .dtasig files.
Stata reference · R reference
datasignature set
signature <- serialize(data,NULL,version=2)
base
Store an exact R serialization for later comparison
R-specific serialized snapshot; not Stata's checksum algorithm, and R metadata is included.
Stata reference · R reference
describe x y
vapply(data[c('x','y')],typeof,character(1))
base
Inspect storage types of selected columns
Stata reference · R reference
describe, short
c(observations=nrow(data),variables=ncol(data))
base
Get dataset dimensions compactly
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
destring s, generate(x)
data$x <- as.numeric(data$s)
base
Parse clean numeric strings
Stata reference · R reference
destring s, generate(x) dpcomma
data$x <- as.numeric(sub(',','.',data$s,fixed=TRUE))
base
Parse a decimal-comma field
Stata reference · R reference
destring s, generate(x) ignore(",")
data$x <- as.numeric(gsub(',','',data$s,fixed=TRUE))
base
Parse numbers containing grouping commas
Stata reference · R reference
destring s, generate(x) percent
data$x <- as.numeric(sub('%$','',data$s))/100
base
Convert percentage text to proportions
Stata reference · R reference
drop if g == 2
data <- data[data$g != 2, , drop=FALSE]
base
Drop a category of rows
Stata reference · R reference
drop if missing(x)
data <- data[!is.na(data$x), , drop=FALSE]
base
Drop rows missing a value
Stata reference · R reference
drop if missing(x, y)
data <- tidyr::drop_na(data, x, y)
tidyr
Drop rows incomplete on selected columns
Stata reference · R reference
drop if x <= 2
data <- dplyr::filter(data, is.na(x) | x > 2)
dplyr
Drop low values while retaining missing rows
Differs from Stata: Stata numeric missing sorts above finite values; the explicit is.na branch preserves those rows.
Stata reference · R reference
drop in 2/4
data <- data[-(2:4), , drop=FALSE]
base
Drop a row interval
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
drop s y
data <- data[setdiff(names(data),c('s','y'))]
base
Remove selected columns
Stata reference · R reference
ds id g, not
setdiff(names(data),c('id','g'))
base
Find columns outside an exclusion list
Stata reference · R reference
ds, has(type numeric)
names(data)[vapply(data,is.numeric,logical(1))]
base
Find names of numeric columns
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
ds, has(type string)
names(data)[vapply(data,is.character,logical(1))]
base
Find names of character columns
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
duplicates drop id, force
data <- data[!duplicated(data$id),,drop=FALSE]
base
Retain the first observation per duplicated key
Stata reference · R reference
duplicates list id
data[duplicated(data$id)|duplicated(data$id,fromLast=TRUE),,drop=FALSE]
base
Inspect all members of duplicated keys
Stata reference · R reference
duplicates report id
counts <- as.integer(table(data$id)); data.frame(copies=sort(unique(counts)),observations=vapply(sort(unique(counts)),function(k) sum(counts[counts==k]),integer(1)),surplus=vapply(sort(unique(counts)),function(k) sum(counts==k)*(k-1L),integer(1)))
base
Summarize copies, observations and duplicate surplus
Stata reference · R reference
duplicates tag id, generate(dup)
data <- dplyr::mutate(data,dup=dplyr::n()-1L,.by=id)
dplyr
Tag all group members with duplicate surplus count
Stata reference · R reference
bysort g: egen z = mean(x)
data <- dplyr::mutate(data,z=mean(x,na.rm=TRUE),.by=g)
dplyr
Attach group means without collapsing rows
Stata reference · R reference
bysort g: egen z = total(x)
data <- dplyr::mutate(data,z=sum(x,na.rm=TRUE),.by=g)
dplyr
Attach group totals without collapsing rows
Stata reference · R reference
egen z = anycount(x y), values(2 4)
data$z <- rowSums(cbind(data$x %in% c(2,4),data$y %in% c(2,4)))
base
Count listed values across columns
Stata reference · R reference
egen z = anymatch(x y), values(2 4)
data$z <- as.integer(data$x %in% c(2,4) | data$y %in% c(2,4))
base
Flag any listed value across columns
Stata reference · R reference
egen z = concat(g s), punct("-")
data$z <- paste(data$g,ifelse(is.na(data$s),'',data$s),sep='-')
base
Concatenate numeric and string columns
Differs from Stata: Treats R NA strings as Stata empty strings; numeric formatting is simple decimal here.
Stata reference · R reference
egen z = count(x)
data$z <- sum(!is.na(data$x))
base
Repeat the nonmissing count in a column
Stata reference · R reference
egen z = cut(x), at(0,3,7)
data$z <- as.numeric(as.character(cut(data$x,breaks=c(0,3,7),right=FALSE,labels=c(0,3))))
base
Bin values and label bins by lower endpoint
Stata reference · R reference
egen z = diff(x y)
data$z <- as.integer(!(data$x==data$y | (is.na(data$x)&is.na(data$y)))); data$z[xor(is.na(data$x),is.na(data$y))] <- 1L
base
Flag differing values across two columns
Differs from Stata: Ordinary missing is handled explicitly; extended Stata missing categories need separate comparison.
Stata reference · R reference
egen z = firstnm(x)
data$z <- data$x[which(!is.na(data$x))[1]]
base
Repeat the first nonmissing value
Stata reference · R reference
egen z = group(g s)
data$z <- as.integer(interaction(data$g,data$s,drop=TRUE,lex.order=TRUE)); data$z[is.na(data$s) | data$s==''] <- NA_integer_
base
Encode combinations of group keys
Differs from Stata: Combination IDs identify groups; exact numeric codes and string collation may differ from Stata.
Stata reference · R reference
egen z = iqr(x)
data$z <- diff(stats::quantile(data$x,c(.25,.75),na.rm=TRUE,type=2))
base
Repeat the interquartile range
Differs from Stata: Uses R quantile type 2 for Stata's default empirical percentile rule.
Stata reference · R reference
egen z = lastnm(x)
data$z <- utils::tail(c(NA_real_, data$x[!is.na(data$x)]), 1)
base
Repeat the last nonmissing value
Stata reference · R reference
egen z = max(x)
data$z <- if (all(is.na(data$x))) NA_real_ else max(data$x, na.rm=TRUE)
base
Repeat the maximum in a column
Stata reference · R reference
egen z = mean(x)
data$z <- mean(data$x,na.rm=TRUE)
base
Repeat the mean in a column
Stata reference · R reference
egen z = median(x)
data$z <- stats::median(data$x,na.rm=TRUE)
base
Repeat the median in a column
Stata reference · R reference
egen z = min(x)
data$z <- if (all(is.na(data$x))) NA_real_ else min(data$x, na.rm=TRUE)
base
Repeat the minimum in a column
Stata reference · R reference
egen z = pc(x)
data$z <- 100*data$x/sum(data$x,na.rm=TRUE)
base
Express values as percentages of the column total
Requires a nonzero observed total; this is a share calculation, not survey estimation.
Stata reference · R reference
egen z = pctile(x), p(25)
data$z <- as.numeric(stats::quantile(data$x,.25,na.rm=TRUE,type=2))
base
Repeat a specified empirical percentile
Differs from Stata: Uses R quantile type 2 for Stata's default empirical percentile rule.
Stata reference · R reference
egen z = rank(x)
data$z <- rank(data$x,na.last='keep',ties.method='average')
base
Rank observed values using average ties
Stata reference · R reference
egen z = rank(x), field
data$z <- rank(-data$x,na.last='keep',ties.method='min')
base
Rank highest value first with competition ties
Stata reference · R reference
egen z = rowmax(x y)
data$z <- pmax(data$x,data$y,na.rm=TRUE)
base
Find the available row maximum
Stata reference · R reference
egen z = rowmean(x y)
data$z <- rowMeans(data[c('x','y')],na.rm=TRUE); data$z[is.nan(data$z)] <- NA_real_
base
Average available values across columns
Stata reference · R reference
egen z = rowmin(x y)
data$z <- pmin(data$x,data$y,na.rm=TRUE)
base
Find the available row minimum
Stata reference · R reference
egen z = rowmiss(x y)
data$z <- rowSums(is.na(data[c('x','y')]))
base
Count missing cells in each row
Stata reference · R reference
egen z = rownonmiss(x y)
data$z <- rowSums(!is.na(data[c('x','y')]))
base
Count observed cells in each row
Stata reference · R reference
egen z = rowtotal(x y)
data$z <- rowSums(data[c('x','y')],na.rm=TRUE)
base
Sum available values across columns
Stata reference · R reference
egen z = rowtotal(x y), missing
data$z <- rowSums(data[c('x','y')],na.rm=TRUE); data$z[rowSums(!is.na(data[c('x','y')]))==0] <- NA_real_
base
Return missing for entirely missing row totals
Stata reference · R reference
egen z = sd(x)
data$z <- stats::sd(data$x,na.rm=TRUE)
base
Repeat the sample standard deviation in a column
Stata reference · R reference
egen z = std(x)
data$z <- as.numeric(scale(data$x))
base
Standardize using the sample standard deviation
Stata reference · R reference
egen z = tag(g)
data$z <- as.integer(!is.na(data$g) & !duplicated(data$g))
base
Tag the first observed row of each group
Stata reference · R reference
egen z = total(x)
data$z <- sum(data$x,na.rm=TRUE)
base
Repeat the sum in a column
Stata reference · R reference
expandcl 2, cluster(g) generate(newg)
parts <- split(data,data$g); data <- do.call(rbind,lapply(seq_along(parts),function(k) do.call(rbind,lapply(1:2,function(j) transform(parts[[k]],newg=(k-1L)*2L+j)))))
base
Duplicate whole groups with fresh group identifiers
Differs from Stata: Validates cluster membership and copy counts; the numeric assignment/order of new IDs may differ from Stata.
Stata reference · R reference
fcollapse (mean) z=x, by(g)
data <- dplyr::summarise(data,z=mean(x,na.rm=TRUE),.by=g)
dplyr
Collapse means with the ftools public helper
Stata reference · R reference
fcollapse (mean) z=x, by(g) merge
data <- dplyr::mutate(data,z=mean(x,na.rm=TRUE),.by=g)
dplyr
Merge fcollapse group summaries back into original rows
Stata reference · R reference
fcollapse (nansum) z=x, by(g)
data <- dplyr::summarise(data,z=if(all(is.na(x))) NA_real_ else sum(x,na.rm=TRUE),.by=g)
dplyr
Preserve missing for entirely missing group sums
Stata reference · R reference
fillin g h
data <- tidyr::complete(data,g,h)
tidyr
Insert absent combinations of categorical keys
Differs from Stata: Returns the rectangularized table without Stata's _fillin indicator; factor levels may add unused R categories.
Stata reference · R reference
fillin g h
data$`_fillin` <- 0L; data <- tidyr::complete(data,g,h,fill=list(`_fillin`=1L))
tidyr
Mark rows inserted during categorical rectangularization
Stata reference · R reference
flevelsof g, local(groups)
groups <- sort(unique(data$g[!is.na(data$g)]))
base
Store observed categories from the ftools levels helper
Stata reference · R reference
fmerge 1:1 id using other.dta, nogenerate
data <- dplyr::full_join(data,other,by='id',relationship='one-to-one')
dplyr
Perform a validated ftools-style one-to-one merge
Requires disjoint non-key column names unless update is explicitly shown. dplyr suffixes overlapping names; ordinary Stata merge preserves master values, including master missing values, on matched rows.
Stata reference · R reference
fralias add score, from(link)
get_score <- function() lookup$score[match(data$id,lookup$id)]
base
Read linked values dynamically without storing a copied column
R accessor-function workflow, not an alias column: call get_score() each time; modifications belong in lookup.
Stata reference · R reference
frget newscore=score, from(link)
data$newscore <- lookup$score[data$link]
base
Rename a linked value when copying it
Value-copy workflow; frame linkage and Stata metadata are not carried into R.
Stata reference · R reference
frget score, from(link)
data$score <- lookup$score[data$link]
base
Copy a value through an established table link
Differs from Stata: Copies values using the precomputed link. Stata display formats and metadata require explicit copying in R.
Stata reference · R reference
frlink 1:1 id, frame(lookup)
stopifnot(!anyDuplicated(data$id),!anyDuplicated(lookup$id)); link <- match(data$id,lookup$id)
base
Validate and construct a one-to-one table link
link is a fixed R object name; unmatched keys produce NA. Rebuild after source changes.
Stata reference · R reference
frlink m:1 id, frame(lookup) generate(link)
stopifnot(!anyDuplicated(lookup$id)); data$link <- match(data$id,lookup$id)
base
Build a many-to-one row link to a lookup table
R match indices are a snapshot and must be rebuilt after lookup row reordering.
Stata reference · R reference
frunalias score
data$score <- lookup$score[match(data$id, lookup$id)]
base
Materialize a dynamically looked-up value as a column
Materialize an ordinary R column snapshot. Requires data and lookup tables with matching id keys and a lookup score column; later lookup changes do not change this column.
Stata reference · R reference
gcollapse (mean) z=x, by(g)
data <- dplyr::summarise(data,z=mean(x,na.rm=TRUE),.by=g)
dplyr
Collapse group means using the gcollapse workflow
Stata reference · R reference
gcollapse (mean) z=x, by(g) freq(n)
data <- dplyr::summarise(data,z=mean(x,na.rm=TRUE),n=dplyr::n(),.by=g)
dplyr
Keep raw group row counts beside collapsed means
Stata reference · R reference
gcollapse (mean) z=x, by(g) merge
data <- dplyr::mutate(data,z=mean(x,na.rm=TRUE),.by=g)
dplyr
Add collapsed group means back to all original rows
Stata reference · R reference
gcollapse (nmissing) n=x, by(g)
data <- dplyr::summarise(data,n=sum(is.na(x)),.by=g)
dplyr
Collapse group missing-value counts
Stata reference · R reference
gcollapse (nunique) n=x, by(g)
data <- dplyr::summarise(data,n=dplyr::n_distinct(x,na.rm=TRUE),.by=g)
dplyr
Collapse group distinct-value counts on complete data
Differs from Stata: Complete values in this fixture; treatment of missing categories is not asserted.
Stata reference · R reference
gcontract g h, freq(n)
data <- dplyr::count(data,g,h,name='n')
dplyr
Count jointly observed category combinations
Stata reference · R reference
gcontract g, freq(n) percent(p)
data <- dplyr::count(data,g,name='n'); data$p <- 100*data$n/sum(data$n)
dplyr
Create category counts and percentages with gcontract
Stata reference · R reference
gdistinct g h
vapply(data[c('g','h')],function(z) length(unique(z[!is.na(z)])),integer(1))
base
Count distinct values separately for several columns
Stata reference · R reference
gdistinct g h, joint
nrow(unique(data[stats::complete.cases(data[c('g','h')]),c('g','h')]))
base
Count distinct complete combinations jointly
Stata reference · R reference
gduplicates drop g h, force
data <- data[!duplicated(data[c('g','h')]),,drop=FALSE]
base
Keep the first row of each compound key
Stata reference · R reference
gduplicates tag g h, generate(dup)
data <- dplyr::mutate(data,dup=dplyr::n()-1L,.by=c(g,h))
dplyr
Tag all duplicates of compound keys
Stata reference · R reference
gegen groupid = group(g h)
data$groupid <- as.integer(interaction(data$g,data$h,drop=TRUE,lex.order=TRUE))
base
Create identifiers for complete combinations of keys
Differs from Stata: Complete numeric keys only; exact identifier ordering follows the demonstrated lexicographic keys.
Stata reference · R reference
gegen tag = tag(g)
data$tag <- as.integer(!is.na(data$g)&!duplicated(data$g))
base
Tag one observation in each nonmissing group
Stata reference · R reference
gegen z = mean(x), by(g)
data <- dplyr::mutate(data,z=mean(x,na.rm=TRUE),.by=g)
dplyr
Attach group means using a gegen-style workflow
Stata reference · R reference
bysort g (id): generate row = _n
data <- dplyr::arrange(data,g,id); data <- dplyr::mutate(data,row=dplyr::row_number(),.by=g)
dplyr
Number observations within sorted groups
Stata reference · R reference
bysort g (id): generate total = sum(x)
data <- dplyr::arrange(data,g,id); data <- dplyr::mutate(data,total=cumsum(replace(x,is.na(x),0)),.by=g)
dplyr
Compute running totals within groups
Stata reference · R reference
bysort g: generate n = _N
data <- dplyr::mutate(data,n=dplyr::n(),.by=g)
dplyr
Attach group row counts
Stata reference · R reference
bysort id (year): generate first = _n == 1
{ data <- dplyr::arrange(data, id, year); dplyr::mutate(data, first = as.integer(dplyr::row_number() == 1L), .by = id) }
dplyr
Mark the first observation within sorted groups
Differs from Stata: Sorts by id and year, then marks one first row per id, including a missing-id group. Ties in year use input order in R; add a tie-break variable for a reproducible cross-system choice.
Stata reference · R reference
generate byte high = x > 3 if x < .
data$high <- ifelse(is.na(data$x),NA_integer_,as.integer(data$x > 3))
base
Create a binary indicator retaining missing values
Stata reference · R reference
generate byte observed = !missing(x)
data$observed <- as.integer(!is.na(data$x))
base
Create a nonmissing indicator
Stata reference · R reference
generate cumulative = sum(x)
data$cumulative <- cumsum(replace(data$x,is.na(data$x),0))
base
Create a running sum ignoring missing values
Stata's generate sum() treats missing contributions as zero, unlike raw cumsum().
Stata reference · R reference
generate double z = x^2
data$z <- data$x^2
base
Square a variable preserving missing values
Stata reference · R reference
generate n = _N
data$n <- nrow(data)
base
Repeat the total row count
Stata reference · R reference
generate prior = x[_n-1]
data$prior <- dplyr::lag(data$x)
dplyr
Shift a column by row position
Differs from Stata: Position-based shift; this does not use time-series spacing or tsset semantics.
Stata reference · R reference
generate row = _n
data$row <- seq_len(nrow(data))
base
Create row numbers
Stata reference · R reference
generate z = x + y
data$z <- data$x + data$y
base
Add columns with missing propagation
Stata reference · R reference
getmata (x y)=X
data <- as.data.frame(X); names(data) <- c('x','y')
base
Convert a matrix into named data columns
Creates a new R table rather than importing from a separate Mata workspace; X is fixed.
Stata reference · R reference
gisid g h, missok
stopifnot(!anyDuplicated(data[c('g','h')]))
base
Validate compound-key uniqueness allowing ordinary missing
Differs from Stata: Ordinary missing is allowed as a key value; extended Stata missing categories are not represented here.
Stata reference · R reference
gisid id
stopifnot(!anyNA(data$id),!anyDuplicated(data$id))
base
Assert a unique complete identifier with gisid
Stata reference · R reference
glevelsof g h
levels <- unique(data[c('g','h')]); levels <- levels[do.call(order,levels),,drop=FALSE]
base
List distinct complete multi-column keys
Differs from Stata: Returns a key table rather than a space-delimited local macro; fixture keys contain no missing values.
Stata reference · R reference
glevelsof g, local(levels)
levels <- sort(unique(data$g[!is.na(data$g)]))
base
Store sorted distinct categories with glevelsof
Stata reference · R reference
gquantiles quartile=x, xtile nquantiles(4)
cuts <- stats::quantile(data$x,c(.25,.5,.75),type=2); data$quartile <- as.integer(cut(data$x,breaks=c(-Inf,cuts,Inf),right=TRUE))
base
Assign four empirical quantile categories
Differs from Stata: Unweighted distinct finite values; uses explicit R type-2 cutoffs and right-closed categories. Ties can prevent equal group sizes.
Stata reference · R reference
gquantiles x, _pctile percentiles(25 50 75)
stats::quantile(data$x,c(.25,.5,.75),type=2)
base
Return selected empirical percentile cutpoints
Differs from Stata: Explicit R type-2 unweighted percentile workflow; no alternative-definition or weighted numerical parity is asserted.
Stata reference · R reference
greshape gather x1 x2, keys(measure) values(value)
data <- tidyr::pivot_longer(data,c(x1,x2),names_to='measure',values_to='value')
tidyr
Gather explicitly named wide columns with greshape
Stata reference · R reference
greshape long x, by(id) keys(wave) dropmiss
data <- tidyr::pivot_longer(data,c(x1,x2),names_to='wave',names_prefix='x',names_transform=list(wave=as.integer),values_to='x',values_drop_na=TRUE)
tidyr
Drop missing measurements while reshaping one stub
Differs from Stata: Single-stub fixed workflow; for multiple stubs drop a row only when every reshaped value is missing.
Stata reference · R reference
greshape spread value, keys(measure)
data <- tidyr::pivot_wider(data,names_from=measure,values_from=value)
tidyr
Spread text-keyed values into columns with greshape
Stata reference · R reference
gsort -x
data <- data[order(-data$x,na.last=FALSE), , drop=FALSE]
base
Sort descending with Stata missing first
Numeric missing sorts first in Stata descending order; use na.last=FALSE deliberately.
Stata reference · R reference
gsort g -y
data <- dplyr::arrange(data, g, dplyr::desc(y))
dplyr
Sort by ascending group and descending value
Stata reference · R reference
gstats winsor x, by(g) cuts(25 75) replace
data <- dplyr::mutate(data,x={b <- stats::quantile(x,c(.25,.75),na.rm=TRUE,type=2); pmax(b[1],pmin(b[2],x))},.by=g)
dplyr
Cap tails separately inside each group
Differs from Stata: Groups use independent unweighted R type-2 cutoffs; all-missing groups require an explicit policy.
Stata reference · R reference
gstats winsor x, cuts(25 75) generate(z)
bounds <- stats::quantile(data$x,c(.25,.75),na.rm=TRUE,type=2); data$z <- pmax(bounds[1],pmin(bounds[2],data$x))
base
Cap both tails at explicitly selected empirical quartiles
Differs from Stata: Unweighted workflow with an explicit R type-2 empirical percentile rule; no cross-software numerical certification is claimed.
Stata reference · R reference
gstats winsor x, cuts(25 75) trim generate(z)
bounds <- stats::quantile(data$x,c(.25,.75),na.rm=TRUE,type=2); data$z <- data$x; data$z[!is.na(data$x) & (data$x<bounds[1] | data$x>bounds[2])] <- NA_real_
base
Set values outside empirical quartiles to missing
Differs from Stata: Trimming sets tails to missing while retaining rows; percentile rule is explicit R type 2 and no weighted parity is asserted.
Stata reference · R reference
gtoplevelsof g, ntop(2)
counts <- dplyr::count(data,g,name='n'); counts <- counts[order(-counts$n,counts$g),]; top <- utils::head(counts,2)
dplyr
Find the two most frequent complete categories
Differs from Stata: Returns the leading categories and counts only; Stata cumulative/Other rows are not generated. gtop is an alias and is not counted separately.
Stata reference · R reference
gunique g h
nrow(unique(data[c('g','h')]))
base
Count unique complete row-key combinations
Differs from Stata: Complete keys in this fixture; unlike gdistinct without joint, gunique treats all listed columns jointly.
Stata reference · R reference
gunique h, by(g) generate(nunique)
data <- dplyr::mutate(data,nunique=dplyr::n_distinct(h),.by=g)
dplyr
Attach distinct-value counts within each group
Differs from Stata: Complete group and value columns in this example; no missing-category behavior is asserted.
Stata reference · R reference
hashsort g -x
data <- data[order(data$g,-data$x,method='radix'),,drop=FALSE]
base
Stably sort by ascending group and descending value
Differs from Stata: Complete numeric keys only; R radix sort preserves original order for equal keys. No comparative speed claim is made.
Stata reference · R reference
insobs 1, after(2)
data <- rbind(data[seq_len(2),,drop=FALSE],data[NA_integer_,,drop=FALSE],data[-seq_len(2),,drop=FALSE])
base
Insert a missing row after a position
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
insobs 1, before(3)
data <- rbind(data[1:2,,drop=FALSE],data[NA_integer_,,drop=FALSE],data[3:6,,drop=FALSE])
base
Insert a missing row before a position
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
insobs 2
data <- rbind(data,data[rep(NA_integer_,2),,drop=FALSE])
base
Append two entirely missing observations
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
inspect x
c(negative=sum(data$x<0,na.rm=TRUE),zero=sum(data$x==0,na.rm=TRUE),positive=sum(data$x>0,na.rm=TRUE),missing=sum(is.na(data$x)))
base
Count signs and missing values
Differs from Stata: Sign/missing counts only; Stata's histogram and integer diagnostic are not included.
Stata reference · R reference
ipolate y x, generate(z)
data$z <- stats::approx(data$x,data$y,xout=data$x,rule=1)$y
base
Keep boundary missing values outside the interpolation range
Stata reference · R reference
isid g h
stopifnot(!anyNA(data[c('g','h')]),!anyDuplicated(data[c('g','h')]))
base
Assert a compound key uniquely identifies rows
Stata reference · R reference
isid id
stopifnot(!anyNA(data$id),!anyDuplicated(data$id))
base
Assert a key is unique and nonmissing
Stata reference · R reference
isid id, missok
stopifnot(!anyDuplicated(data$id))
base
Allow one ordinary missing value in a unique key
Stata reference · R reference
joinby g using other.dta
data <- dplyr::inner_join(data,other,by='g',relationship='many-to-many')
dplyr
Form every matching pair within groups
Stata reference · R reference
joinby g using other.dta, unmatched(master)
data <- dplyr::left_join(data,other,by='g',relationship='many-to-many')
dplyr
Keep unmatched master rows while forming group pairs
Differs from Stata: Returns paired rows without the Stata _merge indicator.
Stata reference · R reference
keep id x
data <- data[c('id','x')]
base
Keep named columns in order
Stata reference · R reference
keep if !missing(x, y)
data <- data[stats::complete.cases(data[c('x','y')]), , drop=FALSE]
base
Keep complete rows on selected columns
Stata reference · R reference
keep if g == 2
data <- dplyr::filter(data, g == 2)
dplyr
Filter to a category with dplyr
Stata reference · R reference
keep if inlist(g, 1, 3)
data <- data[data$g %in% c(1,3), , drop=FALSE]
base
Keep a set of categories
Stata reference · R reference
keep if missing(x)
data <- data[is.na(data$x), , drop=FALSE]
base
Keep rows missing a value
Stata reference · R reference
keep if s != ""
data <- data[!is.na(data$s) & data$s != '', , drop=FALSE]
base
Keep nonempty strings
Differs from Stata: Stata string missing is empty text; this excludes both empty text and R NA.
Stata reference · R reference
keep if x > 2 & x < .
data <- data[!is.na(data$x) & data$x > 2, , drop=FALSE]
base
Keep observed values above a threshold
Stata reference · R reference
keep in 2/4
data <- data[2:4, , drop=FALSE]
base
Keep a row interval by position
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
levelsof g, local(groups)
groups <- sort(unique(data$g[!is.na(data$g)]))
base
Store distinct observed numeric categories
Stata reference · R reference
levelsof x, missing
sort(unique(data$x),na.last=TRUE)
base
List distinct values including ordinary missing
Stata reference · R reference
list id x if g == 2
data[data$g==2,c('id','x'),drop=FALSE]
base
Inspect selected rows and columns
Stata reference · R reference
list id x in 1/3
utils::head(data[c('id','x')],3)
utils
Show selected columns from the first rows
Stata reference · R reference
list in -2/l
utils::tail(data,2)
utils
Show the last rows
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
lookfor income
names(data)[grepl('income',names(data),ignore.case=TRUE)]
base
Search column names without case sensitivity
Differs from Stata: Searches names only; include each column's label attribute to search variable labels too.
Stata reference · R reference
memory
utils::object.size(data)
utils
Measure the memory occupied by one R table
Reports one object's estimated memory, not Stata's process-wide memory allocation report.
Stata reference · R reference
merge 1:1 id using other.dta, generate(status)
data$.master <- TRUE; other$.using <- TRUE; data <- dplyr::full_join(data,other,by='id',relationship='one-to-one'); data$status <- ifelse(is.na(data$.master),2L,ifelse(is.na(data$.using),1L,3L)); data$.master <- NULL; data$.using <- NULL
dplyr
Record master-only, using-only and matched status
Requires disjoint non-key column names unless update is explicitly shown. dplyr suffixes overlapping names; ordinary Stata merge preserves master values, including master missing values, on matched rows.
Stata reference · R reference
merge 1:1 id using other.dta, keep(master match) nogenerate
data <- dplyr::left_join(data,other,by='id',relationship='one-to-one')
dplyr
Keep all master rows in a one-to-one merge
Requires disjoint non-key column names unless update is explicitly shown. dplyr suffixes overlapping names; ordinary Stata merge preserves master values, including master missing values, on matched rows.
Stata reference · R reference
merge 1:1 id using other.dta, keep(match) nogenerate
data <- dplyr::inner_join(data,other,by='id',relationship='one-to-one')
dplyr
Keep only matched keys in a one-to-one merge
Requires disjoint non-key column names unless update is explicitly shown. dplyr suffixes overlapping names; ordinary Stata merge preserves master values, including master missing values, on matched rows.
Stata reference · R reference
merge 1:1 id using other.dta, keepusing(y) nogenerate
data <- dplyr::full_join(data,other[c('id','y')],by='id',relationship='one-to-one')
dplyr
Limit using-table columns during merge
Requires disjoint non-key column names unless update is explicitly shown. dplyr suffixes overlapping names; ordinary Stata merge preserves master values, including master missing values, on matched rows.
Stata reference · R reference
merge 1:1 id using other.dta, nogenerate
stopifnot(!anyDuplicated(data$id),!anyDuplicated(other$id)); data <- dplyr::full_join(data,other,by='id',relationship='one-to-one')
dplyr
Perform a validated one-to-one full merge
Requires disjoint non-key column names unless update is explicitly shown. dplyr suffixes overlapping names; ordinary Stata merge preserves master values, including master missing values, on matched rows.
Stata reference · R reference
merge 1:1 id using other.dta, update nogenerate
data <- dplyr::full_join(data,other,by='id',suffix=c('','.using'),relationship='one-to-one'); data$x <- dplyr::coalesce(data$x,data$x.using); data$x.using <- NULL
dplyr
Fill master missing values from matched using values
Differs from Stata: Shows value update only; Stata update conflict status codes 4/5 are not generated. Requires disjoint non-key column names unless update is explicitly shown. dplyr suffixes overlapping names; ordinary Stata merge preserves master values, including master missing values, on matched rows.
Stata reference · R reference
merge 1:m id using other.dta, nogenerate
data <- dplyr::full_join(data,other,by='id',relationship='one-to-many')
dplyr
Expand unique master keys to multiple matching rows
Requires disjoint non-key column names unless update is explicitly shown. dplyr suffixes overlapping names; ordinary Stata merge preserves master values, including master missing values, on matched rows.
Stata reference · R reference
merge m:1 g using groups.dta, keep(master match) nogenerate
data <- dplyr::left_join(data,groups,by='g',relationship='many-to-one')
dplyr
Attach unique group attributes to many rows
Requires disjoint non-key column names unless update is explicitly shown. dplyr suffixes overlapping names; ordinary Stata merge preserves master values, including master missing values, on matched rows.
Stata reference · R reference
missings dropobs x y, force
data <- data[rowSums(!is.na(data[c('x','y')]))>0,,drop=FALSE]
base
Drop rows missing on every selected numeric variable
Stata reference · R reference
missings dropvars, force
data <- data[!vapply(data,function(z) all(is.na(z)),logical(1))]
base
Drop entirely missing numeric columns
Differs from Stata: Numeric-only fixture; Stata string missing is empty text and would require an additional R test for empty strings.
Stata reference · R reference
missings report x y
colSums(is.na(data[c('x','y')]))
base
Report missing-value counts by numeric variable
Differs from Stata: Numeric columns only. The R result includes zero counts; Stata report defaults to showing counts at least one.
Stata reference · R reference
missings tag x y, generate(nmiss)
data$nmiss <- rowSums(is.na(data[c('x','y')]))
base
Count numeric missing values within each row
Stata reference · R reference
misstable patterns x y
table(apply(is.na(data[c('x','y')]),1,paste0,collapse=''))
base
Count joint missingness patterns
Differs from Stata: TRUE marks missing in the R pattern string; Stata's displayed symbols/order differ.
Stata reference · R reference
misstable summarize x y
colSums(is.na(data[c('x','y')]))
base
Count missing values for each selected column
Stata reference · R reference
mvdecode x, mv(-99 -98)
data$x[data$x %in% c(-99,-98)] <- NA_real_
base
Convert multiple sentinel codes to missing
Stata reference · R reference
mvdecode x, mv(-99=.a)
data$x[data$x %in% -99] <- haven::tagged_na('a')
haven
Convert a sentinel to tagged missing
Differs from Stata: Tagged missing preserves the label but R comparisons still follow NA semantics.
Stata reference · R reference
mvencode x, mv(-99)
data$x[is.na(data$x)] <- -99
base
Encode missing values with a sentinel
Stata reference · R reference
mvencode x, mv(.a=-99)
data$x[haven::is_tagged_na(data$x,'a')] <- -99
haven
Encode one tagged missing category
Stata reference · R reference
order _all, alphabetic
data <- data[sort(names(data))]
base
Alphabetize column order
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
order id, last
data <- dplyr::relocate(data, id, .after=dplyr::last_col())
dplyr
Move a column to the end
Stata reference · R reference
order s, after(id)
data <- dplyr::relocate(data, s, .after=id)
dplyr
Move a column after another
Stata reference · R reference
order y id, first
data <- data[c('y','id',setdiff(names(data),c('y','id')))]
base
Move selected columns to the front
Stata reference · R reference
putmata X=(x y)
X <- as.matrix(data[c('x','y')])
base
Copy numeric columns into an R matrix
R matrix workflow replaces the separate Mata workspace; X is a fixed matrix name.
Stata reference · R reference
putmata X=(x y), omitmissing
X <- as.matrix(data[stats::complete.cases(data[c('x','y')]),c('x','y')])
base
Copy complete numeric rows into a matrix
R matrix workflow replaces Mata; rows are removed jointly over the selected columns.
Stata reference · R reference
range z 0 1 5
data <- data.frame(z=seq(0,1,length.out=5))
base
Create an evenly spaced grid including endpoints
Stata reference · R reference
range z 0 10
data$z <- seq(0,10,length.out=nrow(data))
base
Attach a grid using the current row count
Stata reference · R reference
range z 10 0 6
data <- data.frame(z=seq(10,0,length.out=6))
base
Create a decreasing numeric grid
Stata reference · R reference
rangestat (mean) z=x, interval(key -1 1)
data$z <- vapply(data$key,function(k) mean(data$x[data$key>=k-1 & data$key<=k+1]),numeric(1))
base
Compute a mean over each closed numeric-key neighborhood
Differs from Stata: Small complete-data workflow with inclusive key offsets and self included; quadratic scanning is not intended for large datasets.
Stata reference · R reference
rangestat (mean) z=x, interval(key -1 1) excludeself
data$z <- vapply(seq_len(nrow(data)),function(i) mean(data$x[seq_len(nrow(data))!=i & data$key>=data$key[i]-1 & data$key<=data$key[i]+1]),numeric(1))
base
Exclude the current row from numeric-range means
Differs from Stata: Excludes row identity rather than all tied keys. Every fixture neighborhood has another observation; empty neighborhoods need NA handling.
Stata reference · R reference
rangestat (sum) z=x, interval(key -1 1)
data$z <- vapply(data$key,function(k) sum(data$x[data$key>=k-1 & data$key<=k+1]),numeric(1))
base
Compute a sum over each closed numeric-key neighborhood
Differs from Stata: Complete finite keys/values only in this fixture; missing bounds, by-groups and weights need explicit extensions.
Stata reference · R reference
recast double x
data$x <- as.double(data$x)
base
Convert an integer column to double
Stata reference · R reference
recast long x
data$x <- as.integer(data$x)
base
Store whole-number values as R integers
Differs from Stata: Only use when values are whole numbers in R's integer range; Stata storage ranges differ.
Stata reference · R reference
recode x (1/2=0) (3/6=1), generate(binary)
data$binary <- ifelse(is.na(data$x),NA_real_,ifelse(data$x<=2,0,1))
base
Collapse integer categories to two groups
Differs from Stata: Fixture values are integers 1 through 6; specify additional branches for values outside those ranges.
Stata reference · R reference
recode x (1=10) (2=20), generate(z)
data$z <- data$x; data$z[data$x %in% 1] <- 10; data$z[data$x %in% 2] <- 20
base
Recode selected values and retain all others
Stata reference · R reference
rename (x y) (income hours)
names(data)[match(c('x','y'),names(data))] <- c('income','hours')
base
Rename several columns together
Stata reference · R reference
rename *, lower
names(data) <- tolower(names(data))
base
Lowercase all column names
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
rename *, upper
names(data) <- toupper(names(data))
base
Uppercase all column names
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
rename old* new*
names(data) <- sub('^old','new',names(data))
base
Replace a column-name prefix
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
rename x income
data <- dplyr::rename(data, income=x)
dplyr
Rename a column with dplyr
Stata reference · R reference
replace s = "unknown" if s == ""
data$s[!is.na(data$s) & data$s==''] <- 'unknown'
base
Replace empty text without replacing NA
Differs from Stata: R distinguishes empty text from NA; this example targets empty text only.
Stata reference · R reference
replace x = . if x == 2
data$x[data$x %in% 2] <- NA_real_
base
Convert a sentinel to missing
Stata reference · R reference
replace x = 0 if missing(x)
data$x[is.na(data$x)] <- 0
base
Replace numeric missing by zero
Stata reference · R reference
replace x = x * 100 if g == 1
data$x[data$g %in% 1] <- data$x[data$g %in% 1] * 100
base
Modify values only inside a category
Stata reference · R reference
replace x = y if missing(x)
data$x[is.na(data$x)] <- data$y[is.na(data$x)]
base
Fill missing values from another column
Stata reference · R reference
reshape long x y, i(id) j(wave)
data <- tidyr::pivot_longer(data,cols=c(x1,x2,y1,y2),names_to=c('.value','wave'),names_pattern='([xy])([12])',names_transform=list(wave=as.integer))
tidyr
Reshape multiple parallel measurement stubs
Fixed two-stub example; all name patterns and source names must be changed together.
Stata reference · R reference
reshape long x, i(id) j(wave)
data <- tidyr::pivot_longer(data,cols=c(x1,x2),names_to='wave',names_prefix='x',names_transform=list(wave=as.integer),values_to='x')
tidyr
Convert a wide measurement stub to long rows
Fixed x1/x2 stub example; source names, stub and output names must be changed together.
Stata reference · R reference
reshape wide x, i(id) j(group) string
data <- tidyr::pivot_wider(data,id_cols=id,names_from=group,values_from=x,names_prefix='x')
tidyr
Use text suffixes when widening measurements
Differs from Stata: Fixed string-suffix workflow; pair keys must be unique.
Stata reference · R reference
reshape wide x, i(id) j(wave)
data <- tidyr::pivot_wider(data,id_cols=id,names_from=wave,values_from=x,names_prefix='x')
tidyr
Convert unique long measurements to wide columns
Differs from Stata: Requires unique id-wave pairs; duplicates must be resolved explicitly rather than silently aggregated.
Stata reference · R reference
separate x, by(g)
for (k in sort(unique(data$g))) data[[paste0('x',k)]] <- ifelse(data$g==k,data$x,NA_real_)
base
Create group-specific copies of a numeric column
Stata reference · R reference
separate y, by(g == 1) generate(z)
data$z0 <- ifelse(data$g!=1,data$y,NA_real_); data$z1 <- ifelse(data$g==1,data$y,NA_real_)
base
Separate a column by a binary expression
The generated stub z is fixed here; z0 and z1 are the false and true branches.
Stata reference · R reference
seqvar z = 1/3
data$z <- rep(NA_integer_,nrow(data)); data$z[seq_len(min(3L,nrow(data)))] <- seq_len(min(3L,nrow(data)))
base
Leave remaining rows missing after a short integer sequence
Stata reference · R reference
seqvar z = 1/3 5/7
data$z <- c(1:3,5:7)
base
Create a specified integer sequence with a deliberate gap
Stata reference · R reference
snapshot restore 1
data <- readRDS(path)
base
Restore a temporary data snapshot
Restores an explicitly supplied RDS path rather than a numbered Stata snapshot.
Stata reference · R reference
snapshot save
path <- tempfile(fileext='.rds'); saveRDS(data,path)
base
Save a temporary on-disk data snapshot
Uses an RDS file path rather than Stata's numbered interactive snapshot manager.
Stata reference · R reference
sort g x
data <- data[order(data$g,data$x,na.last=TRUE), , drop=FALSE]
base
Sort lexicographically on two columns
Stata reference · R reference
sort g, stable
data <- data[order(data$g,method='radix'), , drop=FALSE]
base
Keep original order within equal keys
Stata reference · R reference
sort x
data <- data[order(data$x, na.last=TRUE), , drop=FALSE]
base
Sort a numeric column with missing last
Stata reference · R reference
splitsample, generate(sample)
data$sample <- sample(rep(1:2,length.out=nrow(data)))
base
Assign a balanced random half-split
Differs from Stata: Random assignments differ across R and Stata; this fixture has even sample size.
Stata reference · R reference
splitsample, generate(sample) nsplit(3)
data$sample <- sample(rep(1:3,each=nrow(data)/3))
base
Assign three equal random subsamples
Differs from Stata: Requires the fixture row count to be divisible by three; random assignments differ across systems.
Stata reference · R reference
stack x a y b, into(value amount) clear
data <- rbind(data.frame(value=data$x,amount=data$a,`_stack`=1L,check.names=FALSE),data.frame(value=data$y,amount=data$b,`_stack`=2L,check.names=FALSE))
base
Stack pairs of columns together
Stata reference · R reference
stack x y, into(value) clear
data <- data.frame(value=c(data$x,data$y),`_stack`=rep(1:2,each=nrow(data)),check.names=FALSE)
base
Stack two columns vertically with a source indicator
Stata reference · R reference
tostring x, generate(s) format(%06.0f)
data$s <- sprintf('%06.0f',data$x)
base
Format numeric identifiers with leading zeros
Stata reference · R reference
tostring x, generate(s) format(%9.2f)
data$s <- sprintf('%.2f',data$x)
base
Format numeric text to two decimal places
Differs from Stata: R example omits field-width padding; values are rounded for display and stored as text.
Stata reference · R reference
xi i.g
data <- dplyr::select(tidystata::as_dummy(data, g, .names = "index"), -tidyselect::any_of("g_1"))
tidystata
Create indicator variables omitting the lowest category
Differs from Stata: Keeps the original columns and omits the first observed category. Numeric categories are ordered by value; R factors follow their level order, which must match Stata's omitted category. Stata names indicators by category code; R numbers observed categories with .names="index". Use factor(g) in models; xi: interactions are not reproduced.
Stata reference · R reference
xpose, clear
data <- as.data.frame(t(as.matrix(data)))
base
Transpose an entirely numeric table
Differs from Stata: Numeric-only input; R output column names differ from Stata's v1, v2 names.
Stata reference · R reference
xpose, clear varname
oldnames <- names(data); data <- as.data.frame(t(as.matrix(data))); data[['_varname']] <- oldnames
base
Transpose values while retaining original column names
Differs from Stata: Numeric-only input. Original names are copied into _varname; R transposed column names may differ.
Stata reference · R reference

Files and import/export

Stata R Purpose, qualifications and sources
changeeol source.txt destination.txt, eol(unix)
writeBin(charToRaw(paste0(paste(readLines(src),collapse='\n'),'\n')),dst)
base
Normalize a text file to Unix newlines
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
changeeol source.txt destination.txt, eol(windows)
writeBin(charToRaw(paste0(paste(readLines(src),collapse='\r\n'),'\r\n')),dst)
base
Write text using explicit Windows CRLF bytes
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
checksum sample.txt
tools::md5sum(src)
tools
Compute a file integrity digest
MD5 is a workflow alternative: Stata checksum uses POSIX CRC, so digest values are not comparable.
Stata reference · R reference
checksum sample.txt, saving(sample.sum)
digest <- tools::md5sum(src); writeLines(unname(digest),dst)
tools
Save a file digest in a sidecar text file
Writes an R MD5 sidecar, not a Stata .sum file; Stata cannot validate this format as its CRC sidecar.
Stata reference · R reference
copy source.txt destination.txt
file.copy(src,dst,overwrite=FALSE)
base
Copy a local file to a new path
src and dst are temporary paths in this runnable fixture; no network transfer is involved.
Stata reference · R reference
copy source.txt destination.txt, replace
file.copy(src,dst,overwrite=TRUE)
base
Overwrite a destination file with a local copy
Demonstrates overwrite on newly created temporary files only.
Stata reference · R reference
dir "*.csv"
list.files(path,pattern='[.]csv$',full.names=FALSE)
base
List CSV files in a directory
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
dir, all
list.files(path,all.files=TRUE,no..=TRUE)
base
List files including hidden dot files
Differs from Stata: R all.files includes dot files; hidden-file conventions vary by operating system.
Stata reference · R reference
export delimited id x using sample.csv, novarnames replace
utils::write.table(data[c('id','x')],path,sep=',',row.names=FALSE,col.names=FALSE,quote=FALSE,na='')
utils
Export CSV without variable names
Stata reference · R reference
export delimited id x using sample.csv, replace
utils::write.csv(data[c('id','x')],path,row.names=FALSE,na='')
utils
Export selected columns to CSV
Stata reference · R reference
export delimited id x using sample.tsv, delimiters("\t") replace
utils::write.table(data[c('id','x')],path,sep='\t',row.names=FALSE,quote=FALSE,na='')
utils
Export a tab-separated table
Stata reference · R reference
export excel id x using sample.xlsx, firstrow(variables) replace
writexl::write_xlsx(data[c('id','x')],path)
writexl
Export selected columns to an Excel workbook
Stata reference · R reference
export sasxport5 sample.xpt, replace
haven::write_xpt(data,path,version=5,name='SAMPLE')
haven
Export data in SAS XPORT version 5 format
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
export spss using sample.sav, replace
haven::write_sav(data,path)
haven
Export labelled values to an SPSS system file
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
file open handle using sample.txt, read text
file read handle line
file close handle
con <- file(src,open='rt',encoding='UTF-8'); line <- readLines(con,n=1); close(con)
base
Read one line through a text connection
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
file open handle using sample.txt, write text
file write handle "hello" _n
file close handle
con <- file(path,open='wt',encoding='UTF-8'); writeLines('hello',con); close(con)
base
Write and close a UTF-8 text connection
The example closes its own temporary connection explicitly.
Stata reference · R reference
filefilter source.txt destination.txt, from("old") to("new")
writeLines(gsub('old','new',readLines(src),fixed=TRUE),dst,useBytes=TRUE)
base
Replace literal text throughout a small file
Differs from Stata: Line-oriented small-file workflow; binary patterns and large-file streaming are not covered.
Stata reference · R reference
filefilter source.txt destination.txt, from(\t) to(";")
writeLines(gsub('\t',';',readLines(src),fixed=TRUE),dst,useBytes=TRUE)
base
Replace tab separators in a text file
Differs from Stata: Literal small-text-file replacement; quoted delimiters in tabular data need a parser instead.
Stata reference · R reference
findfile sample.txt, path(folder)
found <- list.files(folder,pattern='^sample[.]txt$',full.names=TRUE); stopifnot(length(found)==1L); normalizePath(found,winslash='/')
base
Find a named file inside a specified directory
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
hexdump sample.bin
bytes <- readBin(src,'raw',n=file.info(src)$size); format(bytes)
base
Inspect a file as hexadecimal byte values
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
hexdump sample.bin, analyze tabulate
table(as.integer(readBin(src,'raw',n=file.info(src)$size)))
base
Count byte values in a binary file
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
import delimited using sample.csv, clear
data <- utils::read.csv(path,stringsAsFactors=FALSE)
utils
Import a CSV file with a header
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
import delimited using sample.csv, rowrange(3:4) varnames(nonames) clear
data <- utils::read.csv(path,header=FALSE,skip=2,nrows=2,col.names=c('id','x'))
utils
Read a selected range of text rows
Differs from Stata: Row numbers refer to physical file rows including the header; R column names are fixed in this example.
Stata reference · R reference
import delimited using sample.csv, stringcols(1) clear
data <- utils::read.csv(path,colClasses=c('character','numeric'))
utils
Preserve zero-padded identifiers during import
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
import delimited using sample.csv, varnames(nonames) clear
data <- utils::read.csv(path,header=FALSE,col.names=c('id','x'))
utils
Import a CSV file without a header
Differs from Stata: R column names id and x are supplied explicitly; Stata would choose default names without further renaming.
Stata reference · R reference
import delimited using sample.tsv, delimiters("\t") clear
data <- utils::read.delim(path,stringsAsFactors=FALSE)
utils
Import tab-separated values
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
import excel using sample.xlsx, describe
readxl::excel_sheets(path)
readxl
List worksheet names before importing
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
import excel using sample.xlsx, sheet("Survey") cellrange(A1:B2) firstrow clear
data <- readxl::read_excel(path,sheet='Survey',range='A1:B2')
readxl
Import a bounded Excel cell rectangle
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
import excel using sample.xlsx, sheet("Survey") firstrow clear
data <- readxl::read_excel(path,sheet='Survey')
readxl
Read one named Excel worksheet
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
import sasxport5 sample.xpt, clear
data <- haven::read_xpt(path)
haven
Import a SAS XPORT version 5 file
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
import spss using sample.sav, clear
data <- haven::read_sav(path)
haven
Import an SPSS system file
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
import delimited using sample.csv, clear
data <- utils::read.csv(path,na.strings=c('','.'),stringsAsFactors=FALSE)
utils
Recognize blank and period missing markers on import
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
infile id x using sample.txt, clear
data <- utils::read.table(path,col.names=c('id','x'),header=FALSE)
utils
Import whitespace-separated numeric fields
Free-format example with simple unquoted numeric fields.
Stata reference · R reference
infile str8 name x using sample.txt, clear
data <- utils::read.table(path,col.names=c('name','x'),header=FALSE,stringsAsFactors=FALSE)
utils
Import quoted text and numeric fields
Stata reference · R reference
infix id 1-2 x 3-5 using sample.txt, clear
data <- utils::read.fwf(path,widths=c(2,3),col.names=c('id','x'))
utils
Read adjacent fixed-width numeric fields
Stata reference · R reference
infix str3 code 1-3 x 5-6 using sample.txt, clear
data <- utils::read.fwf(path,widths=c(3,-1,2),col.names=c('code','x'),stringsAsFactors=FALSE)
utils
Read fixed-width fields while skipping a spacer
Stata reference · R reference
jdbc insert id score, table("people")
DBI::dbAppendTable(con,'people',data); observed <- DBI::dbReadTable(con,'people'); DBI::dbDisconnect(con)
DBI
Append controlled rows to an existing SQL table
Requires an existing Stata DSN/JDBC connection for the shown Stata example. The controlled SQLite fixture verifies the SQL/table operation, not ODBC/JDBC driver connection; use an appropriate DBI backend in production.
Stata reference · R reference
jdbc load, table("people")
data <- DBI::dbReadTable(con,'people'); DBI::dbDisconnect(con)
DBI
Load an entire SQL table through a DBI backend
Requires an existing Stata DSN/JDBC connection for the shown Stata example. The controlled SQLite fixture verifies the SQL/table operation, not ODBC/JDBC driver connection; use an appropriate DBI backend in production.
Stata reference · R reference
mkdir work
dir.create(path)
base
Create a directory
The runnable fixture creates a new directory under R's temporary directory.
Stata reference · R reference
odbc describe "people", dsn("research")
fields <- DBI::dbListFields(con,'people'); DBI::dbDisconnect(con)
DBI
Inspect database table field names
Requires an existing Stata DSN/JDBC connection for the shown Stata example. The controlled SQLite fixture verifies the SQL/table operation, not ODBC/JDBC driver connection; use an appropriate DBI backend in production. This row returns names only, not the Stata column-type report.
Stata reference · R reference
odbc load, exec("SELECT id, score FROM people WHERE score >= 20") dsn("research")
data <- DBI::dbGetQuery(con,'SELECT id, score FROM people WHERE score >= 20 ORDER BY id'); DBI::dbDisconnect(con)
DBI
Load selected rows from a SQL query
Requires an existing Stata DSN/JDBC connection for the shown Stata example. The controlled SQLite fixture verifies the SQL/table operation, not ODBC/JDBC driver connection; use an appropriate DBI backend in production.
Stata reference · R reference
odbc query "research"
tables <- DBI::dbListTables(con); DBI::dbDisconnect(con)
DBI
Inspect available tables in a database
Requires an existing Stata DSN/JDBC connection for the shown Stata example. The controlled SQLite fixture verifies the SQL/table operation, not ODBC/JDBC driver connection; use an appropriate DBI backend in production.
Stata reference · R reference
outfile id x using sample.csv, comma replace
utils::write.table(data[c('id','x')],path,sep=',',row.names=FALSE,col.names=FALSE,quote=FALSE,na='.')
utils
Export comma-separated fields without a header
Stata reference · R reference
outfile id x using sample.txt, replace
utils::write.table(data[c('id','x')],path,sep=' ',row.names=FALSE,col.names=FALSE,quote=FALSE,na='.')
utils
Export plain numeric fields with Stata-style missing text
Stata reference · R reference
save sample.dta, replace
haven::write_dta(data,path)
haven
Save a table as a current Stata DTA file
Differs from Stata: R object names are not stored as Stata's active-data state; haven writes supported Stata metadata.
Stata reference · R reference
saveold sample.dta, version(12) replace
haven::write_dta(data,path,version=12)
haven
Write a Stata 12-compatible DTA file
Differs from Stata: Use names accepted by haven's older-format validation; this fixture uses names of at least two characters.
Stata reference · R reference
savespss "data.sav", replace
haven::write_sav(data, path)
haven
Save the data as an SPSS file
Differs from Stata: Community command. haven writes variable and value labels, but rejects Stata tagged missing values (.a, .b) with an error. Convert them explicitly to ordinary NA or to chosen SPSS user-missing codes with haven::labelled_spss() before writing. String widths and display formats may differ.
Stata reference · R reference
setroot
root <- rprojroot::find_root(rprojroot::has_file('.here'),path=child)
rprojroot
Locate a project root from a marker file
Uses the explicit .here marker and a supplied starting path; the Stata command also supports other markers and stores a global macro.
Stata reference · R reference
type sample.txt
readLines(src,encoding='UTF-8')
base
Read lines from a UTF-8 text file
Differs from Stata: Returns text lines; print or cat them for a console display.
Stata reference · R reference
type sample.txt, lines(1)
readLines(src,n=1,encoding='UTF-8')
base
Read only the beginning of a text file
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
unicode convertfile source.txt destination.txt, srcencoding("latin1") dstencoding("utf-8")
text <- readLines(src,encoding='latin1'); writeBin(charToRaw(paste0(iconv(text,from='latin1',to='UTF-8'),'\n')),dst)
base
Convert a Latin-1 text file to UTF-8
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
unzipfile sample.zip
utils::unzip(archive,exdir=destination)
utils
Extract a ZIP archive into a chosen temporary directory
Differs from Stata: R extraction directory is explicit; Stata defaults to the current working directory.
Stata reference · R reference
use id x using sample.dta, clear
data <- haven::read_dta(path,col_select=c('id','x'))
haven
Read selected columns from a DTA file
Stata reference · R reference
use sample.dta in 1/3, clear
data <- haven::read_dta(path,n_max=3)
haven
Read the first observations from a DTA file
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
zipfile sample.txt, saving(sample.zip)
zip::zipr(archive,src)
zip
Create a ZIP archive containing a text file
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference

Labels and metadata

Stata R Purpose, qualifications and sources
char list x[]
attributes(data$x)
base
Inspect custom column characteristics
Returns all R attributes, including any custom metadata.
Stata reference · R reference
char x[source] "questionnaire"
attr(data$x,'source') <- 'questionnaire'
base
Store a custom column characteristic
R attributes serve as local metadata; many transformations do not preserve arbitrary attributes.
Stata reference · R reference
decode x, generate(text)
data$text <- as.character(haven::as_factor(data$x))
haven
Decode numeric value labels to text
Stata reference · R reference
encode s, generate(code)
data$code <- as.integer(factor(data$s,levels=sort(unique(data$s[!is.na(data$s)&data$s!='']))))
base
Encode nonempty categories in sorted order
Differs from Stata: Creates integer codes only. Add a labelled vector or keep the factor to retain category labels; collation is locale-dependent.
Stata reference · R reference
label data "Research sample"
attr(data,'label') <- 'Research sample'
base
Attach a dataset label
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
label define yesno 1 "No" 2 "Yes"
yesno <- c(No=1,Yes=2)
base
Define a reusable value-label mapping
R stores the mapping as a named vector; attach it separately to each labelled column.
Stata reference · R reference
label list yesno
attr(data$x,'labels')
base
Read a column's value-label mapping
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
label values x
data$x <- haven::zap_labels(data$x)
haven
Remove value labels while preserving numeric values
Stata reference · R reference
label values x yesno
data$x <- haven::labelled(data$x,labels=yesno)
haven
Attach a numeric value-label dictionary
Stata reference · R reference
label variable x ""
attr(data$x,'label') <- NULL
base
Remove a variable label
Stata reference · R reference
label variable x "Response"
attr(data$x,'label') <- 'Response'
base
Attach a descriptive variable label
Stata reference · R reference
labelbook
lapply(data,function(z) attr(z,'labels'))
base
Inspect value-label dictionaries by column
Differs from Stata: Lists attached dictionaries; does not reproduce Stata's full multilingual label audit.
Stata reference · R reference
labmask code, values(text)
dictionary <- unique(data[c('code','text')]); stopifnot(!anyDuplicated(dictionary$code)); data$code <- haven::labelled(data$code,stats::setNames(dictionary$code,dictionary$text))
haven
Assign existing text values as numeric value labels
Differs from Stata: Requires a unique text label per observed numeric code; this preserves supplied numeric codes rather than alphabetically encoding text.
Stata reference · R reference
notes list x
attr(data$x,'notes')
base
Read notes attached to a column
Reads a custom R notes attribute; preservation depends on subsequent transformations.
Stata reference · R reference
notes x: Measured at baseline
attr(data$x,'notes') <- 'Measured at baseline'
base
Attach a text note to a column
R attribute workflow; numbered Stata note management is not recreated.
Stata reference · R reference
numlabel, add
labs <- attr(data$x,'labels'); names(labs) <- paste0(unname(labs),'. ',names(labs)); attr(data$x,'labels') <- labs
base
Prefix each label with its numeric code
Fixed workflow example; adapt the object and column names together.
Stata reference · R reference
numlabel, remove
labs <- attr(data$x,'labels'); names(labs) <- sub('^[0-9]+[.] ','',names(labs)); attr(data$x,'labels') <- labs
base
Remove a known numeric-code label prefix
Differs from Stata: Targets the demonstrated positive-integer prefix format; other masks require a matching pattern.
Stata reference · R reference
uselabel using sample.dta, clear
labs <- attr(data$x,'labels'); dictionary <- data.frame(lname='x',value=unname(labs),label=names(labs),trunc=0L)
base
Make a value-label dictionary table
Uses an already imported labelled column. R has no separate Stata label-definition name; lname uses the column name.
Stata reference · R reference

Descriptive tables

Stata R Purpose, qualifications and sources
collapse (count) z=x, by(g)
data <- dplyr::summarise(data,z=sum(!is.na(x)),.by=g)
dplyr
Replace rows with group nonmissing counts
Stata reference · R reference
collapse (first) z=x, by(g)
data <- dplyr::summarise(data,z=dplyr::first(x),.by=g)
dplyr
Replace rows with group first values including missing
Stata reference · R reference
collapse (firstnm) z=x, by(g)
data <- dplyr::summarise(data,z=dplyr::first(x[!is.na(x)]),.by=g)
dplyr
Replace rows with group first nonmissing values
Stata reference · R reference
collapse (last) z=x, by(g)
data <- dplyr::summarise(data,z=dplyr::last(x),.by=g)
dplyr
Replace rows with group last values including missing
Stata reference · R reference
collapse (lastnm) z=x, by(g)
data <- dplyr::summarise(data,z=dplyr::last(x[!is.na(x)]),.by=g)
dplyr
Replace rows with group last nonmissing values
Stata reference · R reference
collapse (max) z=x, by(g)
data <- dplyr::summarise(data, z = if (all(is.na(x))) NA_real_ else max(x, na.rm = TRUE), .by = g)
dplyr
Replace rows with group maxima
Stata reference · R reference
collapse (mean) x [fw=w]
data <- data.frame(x=stats::weighted.mean(data$x,data$w))
stats
Collapse integer-frequency-weighted values to a mean
Differs from Stata: Frequency-weighted mean only; no inference or weighted-variance formula is implied.
Stata reference · R reference
collapse (mean) x y, cw by(g)
data <- data[stats::complete.cases(data[c('x','y')]),]; data <- dplyr::summarise(data,dplyr::across(c(x,y),mean),.by=g)
dplyr
Use common complete cases for group summaries
Stata reference · R reference
collapse (mean) z=x, by(g)
data <- dplyr::summarise(data,z=mean(x,na.rm=TRUE),.by=g)
dplyr
Replace rows with group means
Stata reference · R reference
collapse (median) z=x, by(g)
data <- dplyr::summarise(data,z=stats::median(x,na.rm=TRUE),.by=g)
dplyr
Replace rows with group medians
Stata reference · R reference
collapse (min) z=x, by(g)
data <- dplyr::summarise(data, z = if (all(is.na(x))) NA_real_ else min(x, na.rm = TRUE), .by = g)
dplyr
Replace rows with group minima
Stata reference · R reference
collapse (sum) z=x, by(g)
data <- dplyr::summarise(data,z=sum(x,na.rm=TRUE),.by=g)
dplyr
Replace rows with group totals
Stata reference · R reference
contract g [fw=w], freq(n)
data <- dplyr::summarise(data,n=sum(w),.by=g)
dplyr
Create category counts from integer frequency weights
Stata reference · R reference
contract g h, freq(n)
data <- dplyr::count(data,g,h,name='n')
dplyr
Count observed combinations of two categories
Stata reference · R reference
contract g h, freq(n) zero
data <- as.data.frame(table(data$g,data$h)); names(data) <- c('g','h','n')
base
Include unobserved combinations with zero frequency
Stata reference · R reference
contract g, freq(n)
data <- dplyr::count(data,g,name='n')
dplyr
Replace observations with category frequencies
Stata reference · R reference
contract g, freq(n) cfreq(cn) cpercent(cp)
data <- dplyr::count(data,g,name='n'); data$cn <- cumsum(data$n); data$cp <- 100*data$cn/sum(data$n)
dplyr
Create cumulative frequencies and percentages
Stata reference · R reference
contract g, freq(n) percent(p)
data <- dplyr::count(data,g,name='n'); data$p <- 100*data$n/sum(data$n)
dplyr
Create category frequencies and percentages
Stata reference · R reference
contract g, nomiss
data <- dplyr::count(data[!is.na(data$g)&data$g!='',,drop=FALSE],g,name='_freq')
dplyr
Exclude missing categories before contracting
Differs from Stata: Excludes both empty strings and R NA to match Stata's nonmissing string categories.
Stata reference · R reference
summarize x, detail
stats::quantile(data$x,c(.01,.05,.1,.25,.5,.75,.9,.95,.99),na.rm=TRUE,type=2)
base
Get detailed empirical percentiles
Differs from Stata: Percentile portion of summarize detail, using R type 2; skewness/kurtosis are not returned here.
Stata reference · R reference
summarize x, meanonly
c(n=sum(!is.na(data$x)),mean=mean(data$x,na.rm=TRUE),min=min(data$x,na.rm=TRUE),max=max(data$x,na.rm=TRUE))
base
Compute mean-only summary components
Stata reference · R reference
tab1 g h
lapply(data[c('g','h')],table)
base
Make separate one-way frequency tables
Stata reference · R reference
tab2 g h k
pairs <- utils::combn(c('g','h','k'),2,simplify=FALSE); lapply(pairs,function(p) table(data[[p[1]]],data[[p[2]]]))
base
Make each pairwise contingency table
Stata reference · R reference
tabdisp g h, cellvar(value)
stopifnot(!anyDuplicated(data[c('g','h')])); stats::xtabs(value~g+h,data=data,na.action=stats::na.pass)
stats
Display a complete table of precomputed cell values
Differs from Stata: Requires one row for every cell and unique keys; xtabs would otherwise sum duplicates or fill absent cells with zero.
Stata reference · R reference
tabstat x y, statistics(n mean sd) columns(statistics)
sapply(data[c('x','y')],function(z) c(n=sum(!is.na(z)),mean=mean(z,na.rm=TRUE),sd=stats::sd(z,na.rm=TRUE)))
base
Compare count, mean and spread across numeric columns
Stata reference · R reference
tabstat x, by(g) statistics(n mean)
data |> dplyr::group_by(g) |> dplyr::summarise(n=sum(!is.na(x)),mean=mean(x,na.rm=TRUE),.groups='drop')
dplyr
Summarize nonmissing counts and means by category
Stata reference · R reference
tabstat x, statistics(iqr)
with(data,diff(stats::quantile(x,c(.25,.75),na.rm=TRUE,type=2)))
base
Return the interquartile range as a descriptive statistic
Differs from Stata: Uses the Stata-default empirical percentile rule through R quantile type 2.
Stata reference · R reference
tabstat x, statistics(max)
with(data,max(x,na.rm=TRUE))
base
Return the maximum as a descriptive statistic
Differs from Stata: Unweighted descriptive statistic; no survey or sampling-design correction is applied.
Stata reference · R reference
tabstat x, statistics(mean)
with(data,mean(x,na.rm=TRUE))
base
Return the mean as a descriptive statistic
Differs from Stata: Unweighted descriptive statistic; no survey or sampling-design correction is applied.
Stata reference · R reference
tabstat x, statistics(min)
with(data,min(x,na.rm=TRUE))
base
Return the minimum as a descriptive statistic
Differs from Stata: Unweighted descriptive statistic; no survey or sampling-design correction is applied.
Stata reference · R reference
tabstat x, statistics(n)
with(data,sum(!is.na(x)))
base
Return the nonmissing count as a descriptive statistic
Differs from Stata: Unweighted descriptive statistic; no survey or sampling-design correction is applied.
Stata reference · R reference
tabstat x, statistics(p25)
with(data,as.numeric(stats::quantile(x,.25,na.rm=TRUE,type=2)))
base
Return the 25th percentile as a descriptive statistic
Differs from Stata: Uses the Stata-default empirical percentile rule through R quantile type 2.
Stata reference · R reference
tabstat x, statistics(p50)
with(data,stats::median(x,na.rm=TRUE))
base
Return the median as a descriptive statistic
Differs from Stata: Unweighted descriptive statistic; no survey or sampling-design correction is applied.
Stata reference · R reference
tabstat x, statistics(p75)
with(data,as.numeric(stats::quantile(x,.75,na.rm=TRUE,type=2)))
base
Return the 75th percentile as a descriptive statistic
Differs from Stata: Uses the Stata-default empirical percentile rule through R quantile type 2.
Stata reference · R reference
tabstat x, statistics(range)
with(data,diff(range(x,na.rm=TRUE)))
base
Return the range as a descriptive statistic
Differs from Stata: Unweighted descriptive statistic; no survey or sampling-design correction is applied.
Stata reference · R reference
tabstat x, statistics(sd)
with(data,stats::sd(x,na.rm=TRUE))
base
Return the sample standard deviation as a descriptive statistic
Differs from Stata: Unweighted descriptive statistic; no survey or sampling-design correction is applied.
Stata reference · R reference
tabstat x, statistics(semean)
with(data,stats::sd(x,na.rm=TRUE)/sqrt(sum(!is.na(x))))
base
Return the standard error of the mean as a descriptive statistic
Differs from Stata: Unweighted descriptive statistic; no survey or sampling-design correction is applied.
Stata reference · R reference
tabstat x, statistics(sum)
with(data,sum(x,na.rm=TRUE))
base
Return the sum as a descriptive statistic
Differs from Stata: Unweighted descriptive statistic; no survey or sampling-design correction is applied.
Stata reference · R reference
tabstat x, statistics(variance)
with(data,stats::var(x,na.rm=TRUE))
base
Return the sample variance as a descriptive statistic
Differs from Stata: Unweighted descriptive statistic; no survey or sampling-design correction is applied.
Stata reference · R reference
tabulate g
table(data$g)
base
Count a single categorical variable
Stata reference · R reference
tabulate g [fw=w]
stats::xtabs(w~g,data=data,na.action=stats::na.pass)
stats
Tabulate integer frequency weights
Stata reference · R reference
tabulate g h
table(data$g,data$h)
base
Count a two-way contingency table
Stata reference · R reference
tabulate g h, cell
100*prop.table(table(data$g,data$h))
base
Compute percentages of all table cells
Stata reference · R reference
tabulate g h, column
100*prop.table(table(data$g,data$h),margin=2)
base
Compute percentages within each table column
Stata reference · R reference
tabulate g h, row
100*prop.table(table(data$g,data$h),margin=1)
base
Compute percentages within each table row
Stata reference · R reference
tabulate g, generate(d)
indicators <- tidystata::as_dummy(dplyr::select(data, g), g, .remove = TRUE)
tidystata
Create a full set of category indicators
Differs from Stata: Keeps all observations; a missing category gives NA in every dummy. R returns a separate data frame with category-based names; the Stata stub d is not a templated output name.
Stata reference · R reference
tabulate g, missing
table(data$g,useNA='ifany')
base
Include missing categories in a frequency table
Differs from Stata: Maps R NA to an explicit table category; empty character strings remain a separate R value.
Stata reference · R reference

Models and tests

Stata R Purpose, qualifications and sources
ameans y
c(arithmetic=mean(data$y),geometric=exp(mean(log(data$y))),harmonic=1/mean(1/data$y))
stats
Compare arithmetic, geometric and harmonic means
Differs from Stata: Returns the three point estimates for positive nonmissing values; Stata also reports their confidence intervals.
Stata reference · R reference
biprobit y1 y2 x
VGAM::vglm(cbind(y1,y2)~x,family=VGAM::binom2.rho(),data=data)
VGAM
Fit jointly correlated binary probit equations
Differs from Stata: Both binary equations share x and use a constant latent correlation; rho link parameterizations differ but fitted joint probabilities have the same model meaning.
Stata reference · R reference
centile y, centile(50)
{ fit <- boot::boot(data,function(d,i) unname(stats::quantile(d$y[i],0.5,type=6)),R=499); list(median=fit$t0,interval=boot::boot.ci(fit,type="perc")$percent[4:5]) }
boot
Estimate a median and bootstrap its confidence interval
Point-estimate correspondence; this uses a percentile bootstrap interval, whereas Stata centile defaults to a binomial order-statistic interval.
Stata reference · R reference
contrast r.g
multcomp::glht(fit,linfct=multcomp::mcp(g="Dunnett"))
multcomp
Form group contrasts against the reference category
Differs from Stata: Returns contrast estimates and covariance. Stata contrast defaults to unadjusted tests; summary(glht) defaults to single-step multiplicity adjustment. Use summary(result, test=multcomp::adjusted("none")) for unadjusted p-values.
Stata reference · R reference
cpoisson y x, ul(4)
VGAM::vglm(VGAM::SurvS4(y,status)~x,family=VGAM::cens.poisson(),data=data)
VGAM
Fit a right-censored Poisson count model
Differs from Stata: Fixed right-censoring limit 4; status is one for exact counts and zero for counts known to be at least 4. Censoring must not be treated as truncation.
Stata reference · R reference
elasticnet linear y x z, alpha(0.5)
glmnet::cv.glmnet(as.matrix(data[c("x","z")]),data$y,alpha=0.5,nfolds=10)
glmnet
Fit cross-validated elasticnet linear prediction
Prediction workflow: folds, standardization, penalty grids, loss scaling and lambda selection differ from Stata defaults; coefficients need not match.
Stata reference · R reference
esize twosample y, by(g) cohensd
effectsize::cohens_d(y~g,data=data,pooled_sd=TRUE)
effectsize
Estimate Cohen standardized mean differences for two independent groups
Differs from Stata: Uses pooled SD and first-group minus second-group direction; reverse the sign if the substantive contrast is reversed.
Stata reference · R reference
esizei 30 10 2 40 12 3, cohensd
(10-12)/sqrt(((30-1)*2^2+(40-1)*3^2)/(30+40-2))
stats
Compute a pooled-SD effect size from group summaries
Fixed summary-statistic workflow returns Cohen d only; confidence intervals and Hedges correction are not included.
Stata reference · R reference
icc y id
{ wide <- stats::reshape(data,idvar="id",timevar="rater",direction="wide"); psych::ICC(wide[,-1],lmer=FALSE)$results[1,,drop=FALSE] }
psych
Estimate a one-way individual-measure intraclass correlation
Differs from Stata: Fixed balanced design has three measurements per target. R starts from wide repeated-measure columns; ICC1 is the one-way absolute-agreement individual-measure form.
Stata reference · R reference
lasso linear y x z
glmnet::cv.glmnet(as.matrix(data[c("x","z")]),data$y,alpha=1,nfolds=10)
glmnet
Fit cross-validated lasso linear prediction
Prediction workflow: folds, standardization, penalty grids, loss scaling and lambda selection differ from Stata defaults; coefficients need not match.
Stata reference · R reference
manovatest g
summary(fit,test="Pillai")$stats["g",,drop=FALSE]
stats
Test a factor term in a fitted multivariate model
Differs from Stata: After fitting the corresponding MANOVA model. This R row extracts Pillai; Stata manovatest reports four multivariate statistics.
Stata reference · R reference
nestreg: regress y (x) (z)
{ reduced <- stats::lm(y~x,data=data); full <- stats::lm(y~x+z,data=data); stats::anova(reduced,full) }
stats
Compare successively added regression blocks
Differs from Stata: Compares these two nested OLS fits with a partial F test; it does not implement the general Stata prefix that sequences arbitrary model blocks.
Stata reference · R reference
orthog x z, generate(ox oz)
{ Q <- qr.Q(qr(cbind(1,as.matrix(data[c("x","z")])))); data[c("ox","oz")] <- Q[,-1,drop=FALSE]*sqrt(nrow(data)); data[c("ox","oz")] }
stats
Orthogonalize centered predictor columns in their stated order
Differs from Stata: Unweighted QR gives an orthogonal basis with mean square one; signs can differ from Stata modified Gram-Schmidt output.
Stata reference · R reference
orthpoly x, generate(p1 p2 p3) degree(3)
data[c("p1","p2","p3")] <- stats::poly(data$x,degree=3)*sqrt(nrow(data))
stats
Construct three orthogonal polynomial columns
Differs from Stata: Rescales the R orthonormal basis to mean square one; polynomial signs and stored coefficient conventions may differ.
Stata reference · R reference
predictnl p = invlogit(predict(xb)), se(se)
{ pred <- stats::predict(fit,type="link",se.fit=TRUE); data$p <- stats::plogis(pred$fit); data$se <- data$p*(1-data$p)*pred$se.fit; data[c("p","se")] }
stats
Apply a nonlinear prediction transform with delta-method standard errors
Differs from Stata: Run after a logit GLM. This uses the derivative p*(1-p) and the fitted linear-index standard error.
Stata reference · R reference
pwcompare g, mcompare(tukey)
stats::TukeyHSD(stats::aov(y~g,data=data))$g
stats
Compare all group pairs with Tukey simultaneous intervals
Differs from Stata: After the one-way equal-variance model y on g; R TukeyHSD is not a general replacement for adjusted margins in arbitrary models.
Stata reference · R reference
pwmean y, over(g) mcompare(bonferroni)
stats::pairwise.t.test(data$y,data$g,p.adjust.method="bonferroni",pool.sd=TRUE)
stats
Compare group means using Bonferroni-adjusted pooled tests
Differs from Stata: Uses a common pooled within-group variance and Bonferroni-adjusted pairwise t tests. The returned p-value matrix does not include Stata pairwise mean-difference confidence intervals.
Stata reference · R reference
robvar y, by(g)
car::leveneTest(y~factor(g),data=data,center=stats::median)
car
Test equal group variances using median-centered Levene inference
Differs from Stata: Corresponds to robvar W50; Stata additionally reports mean-centered W0 and 10-percent-trimmed W10.
Stata reference · R reference
runtest y, threshold(0)
{ above <- data$y>0; n1 <- sum(above); n0 <- sum(!above); runs <- 1+sum(diff(above)!=0); expected <- 1+2*n1*n0/(n1+n0); variance <- 2*n1*n0*(2*n1*n0-n1-n0)/((n1+n0)^2*(n1+n0-1)); z <- (runs-expected)/sqrt(variance); c(runs=runs,z=z,p.value=2*stats::pnorm(-abs(z))) }
stats
Test whether a binary threshold sequence has random runs
Differs from Stata: Uses the large-sample uncorrected runs statistic, matching Stata default continuity convention; missing values must be removed before this workflow.
Stata reference · R reference
slogit y x z, dimension(1) baseoutcome(3)
VGAM::rrvglm(y~x+z,family=VGAM::multinomial(refLevel="3"),data=data,Rank=1)
VGAM
Fit a rank-one stereotype multinomial logit model
Differs from Stata: Uses the reduced-rank multinomial-logit form of the one-dimensional Anderson stereotype model. Category score identification, scale and sign conventions can differ.
Stata reference · R reference
symmi 10 8 \ 3 10
stats::mcnemar.test(matrix(c(10,8,3,10),2,byrow=TRUE),correct=FALSE)
stats
Test matched-table symmetry directly from cell counts
Differs from Stata: For this 2-by-2 table the symmetry test is the uncorrected McNemar test. Stata also reports table summaries; this R result is an htest object.
Stata reference · R reference
tnbreg y x, ll(0)
VGAM::vglm(y~x,family=VGAM::posnegbinomial(),data=data)
VGAM
Fit zero-truncated NB2 regression
Differs from Stata: Zero-truncated NB2 with constant size; VGAM size equals 1/alpha. Information-matrix and optimizer conventions can differ.
Stata reference · R reference
tpoisson y x, ll(0)
VGAM::vglm(y~x,family=VGAM::pospoisson(),data=data)
VGAM
Fit zero-truncated Poisson regression
Differs from Stata: Zero-truncation only: fitted values are conditional positive-count means, while log-link coefficients parameterize the latent Poisson lambda.
Stata reference · R reference
truncreg y x, ll(0)
VGAM::vglm(y~x,family=VGAM::posnormal(),data=data)
VGAM
Fit a zero-left-truncated normal regression
Differs from Stata: VGAM posnormal represents the special case of normal observations selected above zero; this example does not cover varying or upper truncation limits.
Stata reference · R reference
ztest y == 20, sd(3)
{ z <- (mean(data$y)-20)/(3/sqrt(nrow(data))); c(z=z,p.value=2*stats::pnorm(-abs(z))) }
stats
Test a mean using a known population standard deviation
Differs from Stata: The value 3 is assumed known as a population SD, not estimated from the sample.
Stata reference · R reference
ztesti 30 10 2 40 12 3
{ z <- (10-12)/sqrt(2^2/30+3^2/40); c(z=z,p.value=2*stats::pnorm(-abs(z))) }
stats
Compare independent means from known-variance summaries
Differs from Stata: Treats the supplied standard deviations as known and uses a normal reference distribution. Returns the z statistic and two-sided p-value, without Stata confidence limits.
Stata reference · R reference

Statistical distributions

Stata R Purpose, qualifications and sources
display F(4,10,2)
stats::pf(2, df1=4, df2=10)
stats
Evaluate the F cumulative probability
Stata reference · R reference
display Fden(4,10,2)
stats::df(2, df1=4, df2=10)
stats
Evaluate the F density
Stata reference · R reference
display Ftail(4,10,2)
stats::pf(2, df1=4, df2=10, lower.tail=FALSE)
stats
Evaluate the F upper-tail probability
Stata reference · R reference
display betaden(2,3,0.4)
stats::dbeta(0.4, shape1=2, shape2=3)
stats
Evaluate the beta density
Stata reference · R reference
display binomial(10,3,0.4)
stats::pbinom(3, size=10, prob=0.4)
stats
Compute an inclusive binomial lower tail
Stata reference · R reference
display binomialp(10,3,0.4)
stats::dbinom(3, size=10, prob=0.4)
stats
Evaluate a binomial probability mass
Stata reference · R reference
display binomialtail(10,3,0.4)
stats::pbinom(2, size=10, prob=0.4, lower.tail=FALSE)
stats
Compute an inclusive binomial upper tail
Stata includes k in the upper tail; R lower.tail=FALSE excludes its q argument, so use k-1.
Stata reference · R reference
display binormal(0,0,0.4)
as.numeric(mvtnorm::pmvnorm(upper=c(0,0),corr=matrix(c(1,0.4,0.4,1),2)))
mvtnorm
Evaluate a correlated bivariate normal probability
Differs from Stata: Evaluates a bivariate normal probability using mvtnorm numerical integration. Integration tolerance and numerical rounding differ from the Stata distribution function.
Stata reference · R reference
display cauchy(1,2,3)
stats::pcauchy(3, location=1, scale=2)
stats
Evaluate the Cauchy cumulative probability
Stata reference · R reference
display cauchyden(1,2,3)
stats::dcauchy(3, location=1, scale=2)
stats
Evaluate the Cauchy density
Stata reference · R reference
display cauchytail(1,2,3)
stats::pcauchy(3, location=1, scale=2, lower.tail=FALSE)
stats
Evaluate the Cauchy upper-tail probability
Stata reference · R reference
display chi2(4,3)
stats::pchisq(3, df=4)
stats
Evaluate the chi-squared cumulative probability
Stata reference · R reference
display chi2den(4,3)
stats::dchisq(3, df=4)
stats
Evaluate the chi-squared density
Stata reference · R reference
display chi2tail(4,3)
stats::pchisq(3, df=4, lower.tail=FALSE)
stats
Evaluate the chi-squared upper-tail probability
Stata reference · R reference
corr2data x y, n(100)
stats::setNames(as.data.frame(MASS::mvrnorm(n=100,mu=c(0,0),Sigma=diag(2),empirical=TRUE)),c("x","y"))
MASS
Generate pseudo-data with exactly specified sample moments
Differs from Stata: empirical=TRUE imposes the sample mean and covariance; such pseudo-data are not independent random draws.
Stata reference · R reference
drawnorm x y, n(100)
stats::setNames(as.data.frame(MASS::mvrnorm(n=100,mu=c(0,0),Sigma=diag(2))),c("x","y"))
MASS
Draw independent standard normal columns jointly
Differs from Stata: Random streams differ; R returns a data frame of generated columns.
Stata reference · R reference
display exponential(2,3)
stats::pexp(3, rate=1/2)
stats
Evaluate the exponential cumulative probability
Stata reference · R reference
display exponentialden(2,3)
stats::dexp(3, rate=1/2)
stats
Evaluate the exponential density
Stata reference · R reference
display exponentialtail(2,3)
stats::pexp(3, rate=1/2, lower.tail=FALSE)
stats
Evaluate the exponential upper-tail probability
Stata reference · R reference
display gammaden(3,1,0,2)
stats::dgamma(2, shape=3)
stats
Evaluate the gamma density
Stata reference · R reference
display gammaden(3,2,1,5)
stats::dgamma(5-1, shape=3, scale=2)
stats
Evaluate a shifted gamma density
Stata reference · R reference
display gammap(3,2)
stats::pgamma(2, shape=3)
stats
Evaluate the gamma cumulative probability
Stata reference · R reference
display gammaptail(3,2)
stats::pgamma(2, shape=3, lower.tail=FALSE)
stats
Evaluate the gamma upper-tail probability
Stata reference · R reference
display hypergeometric(20,8,5,3)
stats::phyper(3, m=8, n=12, k=5)
stats
Compute an inclusive hypergeometric lower tail
Stata reference · R reference
display hypergeometricp(20,8,5,3)
stats::dhyper(3, m=8, n=12, k=5)
stats
Evaluate a hypergeometric probability mass
Stata reference · R reference
display ibeta(2,3,0.4)
stats::pbeta(0.4, shape1=2, shape2=3)
stats
Evaluate the beta cumulative probability
Stata reference · R reference
display ibetatail(2,3,0.4)
stats::pbeta(0.4, shape1=2, shape2=3, lower.tail=FALSE)
stats
Evaluate the beta upper-tail probability
Stata reference · R reference
display invF(4,10,0.9)
stats::qf(0.9, df1=4, df2=10)
stats
Find the F 90th percentile
Stata reference · R reference
display invFtail(4,10,0.9)
stats::qf(0.9, df1=4, df2=10, lower.tail=FALSE)
stats
Find a F upper-tail critical value
Stata reference · R reference
display invbinomial(10,3,0.5)
stats::qbeta(0.5, shape1=4, shape2=7, lower.tail=FALSE)
stats
Solve a binomial CDF for its success probability
These Stata inverse functions solve for a distribution parameter, not a discrete outcome quantile.
Stata reference · R reference
display invbinomialtail(10,3,0.5)
stats::qbeta(0.5, shape1=3, shape2=8)
stats
Solve an inclusive binomial tail for success probability
These Stata inverse functions solve for a distribution parameter, not a discrete outcome quantile.
Stata reference · R reference
display invcauchy(1,2,0.9)
stats::qcauchy(0.9, location=1, scale=2)
stats
Find the Cauchy 90th percentile
Stata reference · R reference
display invcauchytail(1,2,0.9)
stats::qcauchy(0.9, location=1, scale=2, lower.tail=FALSE)
stats
Find a Cauchy upper-tail critical value
Stata reference · R reference
display invchi2(4,0.9)
stats::qchisq(0.9, df=4)
stats
Find the chi-squared 90th percentile
Stata reference · R reference
display invchi2tail(4,0.9)
stats::qchisq(0.9, df=4, lower.tail=FALSE)
stats
Find a chi-squared upper-tail critical value
Stata reference · R reference
display invexponential(2,0.9)
stats::qexp(0.9, rate=1/2)
stats
Find the exponential 90th percentile
Stata reference · R reference
display invexponentialtail(2,0.9)
stats::qexp(0.9, rate=1/2, lower.tail=FALSE)
stats
Find a exponential upper-tail critical value
Stata reference · R reference
display invgammap(3,0.9)
stats::qgamma(0.9, shape=3)
stats
Find the gamma 90th percentile
Stata reference · R reference
display invgammaptail(3,0.9)
stats::qgamma(0.9, shape=3, lower.tail=FALSE)
stats
Find a gamma upper-tail critical value
Stata reference · R reference
display invibeta(2,3,0.9)
stats::qbeta(0.9, shape1=2, shape2=3)
stats
Find the beta 90th percentile
Stata reference · R reference
display invibetatail(2,3,0.9)
stats::qbeta(0.9, shape1=2, shape2=3, lower.tail=FALSE)
stats
Find a beta upper-tail critical value
Stata reference · R reference
display invlogistic(0.8)
stats::qlogis(0.8)
stats
Convert probability to log odds
Stata reference · R reference
display invlogistic(1,2,0.9)
stats::qlogis(0.9, location=1, scale=2)
stats
Find the logistic 90th percentile
Stata reference · R reference
display invlogistictail(1,2,0.9)
stats::qlogis(0.9, location=1, scale=2, lower.tail=FALSE)
stats
Find a logistic upper-tail critical value
Stata reference · R reference
display invnF(4,20,2,0.9)
stats::qf(0.9, df1=4, df2=20, ncp=2)
stats
Find a nF noncentral critical value
Stata reference · R reference
display invnFtail(4,20,2,0.9)
stats::qf(0.9, df1=4, df2=20, ncp=2, lower.tail=FALSE)
stats
Find a nF noncentral upper-tail critical value
Stata reference · R reference
display invnbinomial(4,3,0.5)
stats::qbeta(0.5, shape1=4, shape2=4)
stats
Solve a negative-binomial CDF for success probability
These Stata inverse functions solve for a distribution parameter, not a discrete outcome quantile.
Stata reference · R reference
display invnbinomialtail(4,3,0.5)
stats::qbeta(0.5, shape1=4, shape2=3, lower.tail=FALSE)
stats
Solve a negative-binomial tail for success probability
These Stata inverse functions solve for a distribution parameter, not a discrete outcome quantile.
Stata reference · R reference
display invnchi2(4,2,0.9)
stats::qchisq(0.9, df=4, ncp=2)
stats
Find a nchi2 noncentral critical value
Stata reference · R reference
display invnchi2tail(4,2,0.9)
stats::qchisq(0.9, df=4, ncp=2, lower.tail=FALSE)
stats
Find a nchi2 noncentral upper-tail critical value
Stata reference · R reference
display invnibeta(2,3,2,0.9)
stats::qbeta(0.9, shape1=2, shape2=3, ncp=2)
stats
Find a nibeta noncentral critical value
Stata reference · R reference
display invnormal(0.9)
stats::qnorm(0.9)
stats
Find the standard normal 90th percentile
Stata reference · R reference
display invnt(20,2,0.9)
stats::qt(0.9, df=20, ncp=2)
stats
Find a nt noncentral critical value
Stata reference · R reference
display invnttail(20,2,0.9)
stats::qt(0.9, df=20, ncp=2, lower.tail=FALSE)
stats
Find a nt noncentral upper-tail critical value
Stata reference · R reference
display invpoisson(3,0.5)
stats::qgamma(0.5, shape=4, lower.tail=FALSE)
stats
Solve a Poisson CDF for its mean
These Stata inverse functions solve for a distribution parameter, not a discrete outcome quantile.
Stata reference · R reference
display invpoissontail(3,0.5)
stats::qgamma(0.5, shape=3)
stats
Solve an inclusive Poisson tail for its mean
These Stata inverse functions solve for a distribution parameter, not a discrete outcome quantile.
Stata reference · R reference
display invt(10,0.9)
stats::qt(0.9, df=10)
stats
Find the Student t 90th percentile
Stata reference · R reference
display invttail(10,0.9)
stats::qt(0.9, df=10, lower.tail=FALSE)
stats
Find a Student t upper-tail critical value
Stata reference · R reference
display invtukeyprob(4,20,0.95)
stats::qtukey(0.95, nmeans=4, df=20)
stats
Find a Tukey simultaneous-comparison critical value
Differs from Stata: Uses the studentized-range quantile from qtukey. R and Stata implement different numerical approximations; tested inputs differed by about 2.5e-8, so compare within numerical tolerance rather than exact equality.
Stata reference · R reference
display invweibull(2,3,0.9)
stats::qweibull(0.9, shape=2, scale=3)
stats
Find the Weibull 90th percentile
Stata reference · R reference
display invweibullph(2,0.5,0.9)
stats::qweibull(0.9, shape=2, scale=0.5^(-1/2))
stats
Find a PH Weibull percentile
Stata reference · R reference
display invweibullphtail(2,0.5,0.1)
stats::qweibull(0.1, shape=2, scale=0.5^(-1/2), lower.tail=FALSE)
stats
Find a PH Weibull upper-tail quantile
Stata reference · R reference
display invweibulltail(2,3,0.9)
stats::qweibull(0.9, shape=2, scale=3, lower.tail=FALSE)
stats
Find a Weibull upper-tail critical value
Stata reference · R reference
display lncauchyden(1,2,3)
stats::dcauchy(3, location=1, scale=2, log=TRUE)
stats
Evaluate a Cauchy log density
Stata reference · R reference
display lnigammaden(3,2,4)
stats::dgamma(1/4,shape=3,rate=2,log=TRUE)-2*log(4)
stats
Evaluate an inverse-gamma log density
Differs from Stata: Uses the reciprocal-gamma change of variables with its log-Jacobian. Match Stata shape and scale parameterization; numerical tail underflow can differ.
Stata reference · R reference
matrix M = (0,0)
matrix V = I(2)
matrix X = (1,2)
display lnmvnormalden(M,V,X)
mvtnorm::dmvnorm(x=c(1,2),mean=c(0,0),sigma=diag(2),log=TRUE)
mvtnorm
Evaluate a multivariate normal log density
Differs from Stata: Fixed example uses mean M=(0,0), covariance V=I(2), and evaluation vector X=(1,2).
Stata reference · R reference
display lnnormal(-8)
stats::pnorm(-8, log.p=TRUE)
stats
Compute a stable extreme normal log probability
Stata reference · R reference
display lnnormalden(3,1,2)
stats::dnorm(3, mean=1, sd=2, log=TRUE)
stats
Evaluate a normal log density with location and scale
Stata reference · R reference
display logistic(0.7)
stats::plogis(0.7)
stats
Convert log odds to probability
Stata reference · R reference
display logistic(1,2,3)
stats::plogis(3, location=1, scale=2)
stats
Evaluate the logistic cumulative probability
Stata reference · R reference
display logisticden(1,2,3)
stats::dlogis(3, location=1, scale=2)
stats
Evaluate the logistic density
Stata reference · R reference
display logistictail(1,2,3)
stats::plogis(3, location=1, scale=2, lower.tail=FALSE)
stats
Evaluate the logistic upper-tail probability
Stata reference · R reference
display nF(4,20,2,1.5)
stats::pf(1.5, df1=4, df2=20, ncp=2)
stats
Evaluate the nF noncentral CDF
Stata reference · R reference
display nFden(4,20,2,1.5)
stats::df(1.5, df1=4, df2=20, ncp=2)
stats
Evaluate the nF noncentral density
Stata reference · R reference
display nFtail(4,20,2,1.5)
stats::pf(1.5, df1=4, df2=20, ncp=2, lower.tail=FALSE)
stats
Evaluate the nF noncentral upper tail
Stata reference · R reference
display nbetaden(2,3,2,0.4)
stats::dbeta(0.4, shape1=2, shape2=3, ncp=2)
stats
Evaluate the nibeta noncentral density
Stata reference · R reference
display nbinomial(4,3,0.6)
stats::pnbinom(3, size=4, prob=0.6)
stats
Compute an inclusive nbinomial lower tail
Stata reference · R reference
display nbinomialp(4,3,0.6)
stats::dnbinom(3, size=4, prob=0.6)
stats
Evaluate a nbinomial probability mass
Stata reference · R reference
display nbinomialtail(4,3,0.6)
stats::pnbinom(2, size=4, prob=0.6, lower.tail=FALSE)
stats
Compute an inclusive nbinomial upper tail
Stata includes k in the upper tail; R lower.tail=FALSE excludes its q argument, so use k-1.
Stata reference · R reference
display nchi2(4,2,3)
stats::pchisq(3, df=4, ncp=2)
stats
Evaluate the nchi2 noncentral CDF
Stata reference · R reference
display nchi2den(4,2,3)
stats::dchisq(3, df=4, ncp=2)
stats
Evaluate the nchi2 noncentral density
Stata reference · R reference
display nchi2tail(4,2,3)
stats::pchisq(3, df=4, ncp=2, lower.tail=FALSE)
stats
Evaluate the nchi2 noncentral upper tail
Stata reference · R reference
display nibeta(2,3,2,0.4)
stats::pbeta(0.4, shape1=2, shape2=3, ncp=2)
stats
Evaluate the nibeta noncentral CDF
Stata reference · R reference
display normal(0.7)
stats::pnorm(0.7)
stats
Evaluate the standard normal cumulative probability
Stata reference · R reference
display normalden(0.7)
stats::dnorm(0.7)
stats
Evaluate the standard normal density
Stata reference · R reference
display normalden(3,1,2)
stats::dnorm(3, mean=1, sd=2)
stats
Evaluate a normal density with location and scale
Stata reference · R reference
display npnF(4,20,2,0.5)
stats::uniroot(function(ncp) stats::pf(2,df1=4,df2=20,ncp=ncp)-0.5,c(0,50),tol=1e-10)$root
stats
Solve a noncentral F probability for noncentrality
Differs from Stata: Numerically inverts the noncentral F CDF over the displayed bracket. Other inputs can require a different bracket; solver tolerances differ from Stata.
Stata reference · R reference
display npnchi2(4,8,0.5)
stats::uniroot(function(ncp) stats::pchisq(8,df=4,ncp=ncp)-0.5,c(0,50),tol=1e-10)$root
stats
Solve a noncentral chi-squared probability for noncentrality
Differs from Stata: Numerically inverts the noncentral chi-square CDF over the displayed noncentrality bracket. Other inputs may need a wider bracket; Stata performs its own domain validation and inversion.
Stata reference · R reference
display npnt(20,2,0.5)
stats::uniroot(function(ncp) stats::pt(2,df=20,ncp=ncp)-0.5,c(0,4),tol=1e-10)$root
stats
Solve a noncentral t probability for noncentrality
Differs from Stata: Numerically inverts the noncentral t CDF over the displayed bracket. Negative or larger noncentralities require different bounds; solver tolerances differ from Stata.
Stata reference · R reference
display nt(20,2,1.5)
stats::pt(1.5, df=20, ncp=2)
stats
Evaluate the nt noncentral CDF
Stata reference · R reference
display nttail(20,2,1.5)
stats::pt(1.5, df=20, ncp=2, lower.tail=FALSE)
stats
Evaluate the nt noncentral upper tail
Stata reference · R reference
display poisson(2,3)
stats::ppois(3, lambda=2)
stats
Compute an inclusive poisson lower tail
Stata reference · R reference
display poissonp(2,3)
stats::dpois(3, lambda=2)
stats
Evaluate a poisson probability mass
Stata reference · R reference
display poissontail(2,3)
stats::ppois(2, lambda=2, lower.tail=FALSE)
stats
Compute an inclusive poisson upper tail
Stata includes k in the upper tail; R lower.tail=FALSE excludes its q argument, so use k-1.
Stata reference · R reference
generate draw = rbeta(2,3)
stats::rbeta(1000,2,3)
stats
Simulate rbeta variates
Differs from Stata: The same seed does not produce matching draws across Stata and R.
Stata reference · R reference
generate draw = rbinomial(10,0.4)
stats::rbinom(1000,10,0.4)
stats
Simulate rbinomial variates
Differs from Stata: The same seed does not produce matching draws across Stata and R.
Stata reference · R reference
generate draw = rcauchy(1,2)
stats::rcauchy(1000,1,2)
stats
Simulate rcauchy variates
Differs from Stata: The same seed does not produce matching draws across Stata and R.
Stata reference · R reference
generate draw = rchi2(4)
stats::rchisq(1000,4)
stats
Simulate rchi2 variates
Differs from Stata: The same seed does not produce matching draws across Stata and R.
Stata reference · R reference
generate draw = rexponential(2)
stats::rexp(1000,rate=1/2)
stats
Simulate rexponential variates
Differs from Stata: The same seed does not produce matching draws across Stata and R.
Stata reference · R reference
generate draw = rgamma(3,2)
stats::rgamma(1000,shape=3,scale=2)
stats
Simulate rgamma variates
Differs from Stata: The same seed does not produce matching draws across Stata and R.
Stata reference · R reference
generate draw = rhypergeometric(20,8,5)
stats::rhyper(1000,m=8,n=12,k=5)
stats
Simulate rhypergeometric variates
Differs from Stata: The same seed does not produce matching draws across Stata and R.
Stata reference · R reference
generate draw = rlogistic(1,2)
stats::rlogis(1000,location=1,scale=2)
stats
Simulate rlogistic variates
Differs from Stata: The same seed does not produce matching draws across Stata and R.
Stata reference · R reference
generate draw = rnbinomial(4,0.6)
stats::rnbinom(1000,size=4,prob=0.6)
stats
Simulate rnbinomial variates
Differs from Stata: The same seed does not produce matching draws across Stata and R.
Stata reference · R reference
generate draw = rpoisson(2)
stats::rpois(1000,lambda=2)
stats
Simulate rpoisson variates
Differs from Stata: The same seed does not produce matching draws across Stata and R.
Stata reference · R reference
generate draw = rt(20)
stats::rt(1000,df=20)
stats
Simulate rt variates
Differs from Stata: The same seed does not produce matching draws across Stata and R.
Stata reference · R reference
generate draw = rweibull(2,3)
stats::rweibull(1000,shape=2,scale=3)
stats
Simulate rweibull variates
Differs from Stata: The same seed does not produce matching draws across Stata and R.
Stata reference · R reference
display t(10,1.2)
stats::pt(1.2, df=10)
stats
Evaluate the Student t cumulative probability
Stata reference · R reference
display tden(10,1.2)
stats::dt(1.2, df=10)
stats
Evaluate the Student t density
Stata reference · R reference
display ttail(10,1.2)
stats::pt(1.2, df=10, lower.tail=FALSE)
stats
Evaluate the Student t upper-tail probability
Stata reference · R reference
display tukeyprob(4,20,3)
stats::ptukey(3, nmeans=4, df=20)
stats
Evaluate a studentized-range cumulative probability
Stata reference · R reference
display weibull(2,3,1,5)
stats::pweibull(5-1, shape=2, scale=3)
stats
Evaluate a shifted Weibull cumulative probability
Stata reference · R reference
display weibull(2,3,4)
stats::pweibull(4, shape=2, scale=3)
stats
Evaluate the Weibull cumulative probability
Stata reference · R reference
display weibullden(2,3,4)
stats::dweibull(4, shape=2, scale=3)
stats
Evaluate the Weibull density
Stata reference · R reference
display weibullph(2,0.5,3)
stats::pweibull(3, shape=2, scale=0.5^(-1/2))
stats
Use the proportional-hazards Weibull parameterization
Stata reference · R reference
display weibullphden(2,0.5,3)
stats::dweibull(3, shape=2, scale=0.5^(-1/2))
stats
Evaluate a PH Weibull density
Stata reference · R reference
display weibullphtail(2,0.5,3)
stats::pweibull(3, shape=2, scale=0.5^(-1/2), lower.tail=FALSE)
stats
Evaluate a PH Weibull survivor probability
Stata reference · R reference
display weibulltail(2,3,4)
stats::pweibull(4, shape=2, scale=3, lower.tail=FALSE)
stats
Evaluate the Weibull upper-tail probability
Stata reference · R reference

Models and estimation

Stata R Purpose, qualifications and sources
betareg share x, link(cloglog)
betareg::betareg(share~x,data=data,link="cloglog",type="ML",link.phi="log")
betareg
Fit beta regression with a cloglog mean link
Differs from Stata: Uses ordinary ML with a log link for precision, matching Stata slink(log). Without link.phi="log", betareg reports constant phi on the identity scale while Stata reports ln(phi). Responses must lie strictly inside (0,1).
Stata reference · R reference
betareg share x, link(logit)
betareg::betareg(share~x,data=data,link="logit",type="ML",link.phi="log")
betareg
Fit beta regression with a logit mean link
Differs from Stata: Uses ordinary ML with a log link for precision, matching Stata slink(log). Without link.phi="log", betareg reports constant phi on the identity scale while Stata reports ln(phi). Responses must lie strictly inside (0,1).
Stata reference · R reference
betareg share x, link(probit)
betareg::betareg(share~x,data=data,link="probit",type="ML",link.phi="log")
betareg
Fit beta regression with a probit mean link
Differs from Stata: Uses ordinary ML with a log link for precision, matching Stata slink(log). Without link.phi="log", betareg reports constant phi on the identity scale while Stata reports ln(phi). Responses must lie strictly inside (0,1).
Stata reference · R reference
betareg share x, scale(z) slink(log)
betareg::betareg(share~x|z,data=data,link="logit",link.phi="log",type="ML")
betareg
Model beta-regression precision using a covariate
Differs from Stata: Uses a log link for precision; align Stata scale-link parameterization before numerical comparison.
Stata reference · R reference
binreg b i.g, or
stats::glm(b ~ factor(g),data=data,family=stats::binomial(link="logit"))
stats
Fit binomial regression on the or scale
Differs from Stata: Risk-ratio and risk-difference models can encounter boundary and convergence problems; inspect fitted probabilities.
Stata reference · R reference
binreg b i.g, rd
stats::glm(b ~ factor(g),data=data,family=stats::binomial(link="identity"))
stats
Fit binomial regression on the rd scale
Differs from Stata: Risk-ratio and risk-difference models can encounter boundary and convergence problems; inspect fitted probabilities.
Stata reference · R reference
binreg b i.g, rr
stats::glm(b ~ factor(g),data=data,family=stats::binomial(link="log"))
stats
Fit binomial regression on the rr scale
Differs from Stata: Risk-ratio and risk-difference models can encounter boundary and convergence problems; inspect fitted probabilities.
Stata reference · R reference
boxcox y x z, model(lhsonly)
MASS::boxcox(y ~ x+z,data=data,lambda=seq(-1,1,by=0.1),plotit=FALSE)
MASS
Profile the Box-Cox response transformation parameter
Profiles a grid of response-transform parameters; this does not implement all Stata boxcox predictor-transform models.
Stata reference · R reference
bsqreg y x z, reps(99)
{ fit <- quantreg::rq(y~x+z,data=data,tau=0.5); summary(fit,se="boot",R=99) }
quantreg
Bootstrap quantile-regression inference
Differs from Stata: Uses 99 bootstrap replications for quantile-regression inference. R and Stata random streams and resampling implementations differ, so bootstrap standard errors will not be identical.
Stata reference · R reference
cloglog b x z
stats::glm(b ~ x + z,data=data,family=stats::binomial(link="cloglog"))
stats
Fit cloglog regression
Differs from Stata: R uses the complementary log-log link. Match the event category and complete cases; the GLM result object and convergence tolerances differ from Stata cloglog.
Stata reference · R reference
cloglog b x z, noconstant
stats::glm(b ~ x + z - 1,data=data,family=stats::binomial(link="cloglog"))
stats
Fit cloglog without an intercept
Differs from Stata: R uses the complementary log-log link. Match the event category and complete cases; the GLM result object and convergence tolerances differ from Stata cloglog.
Stata reference · R reference
constraint define 1 x = z
cnsreg y x z, constraints(1)
{ fit <- stats::lm(y~I(x+z),data=data); c(intercept=unname(stats::coef(fit)[1]),x=unname(stats::coef(fit)[2]),z=unname(stats::coef(fit)[2])) }
stats
Fit OLS with two coefficients constrained to equality
Fixed workflow. First define constraint 1 x = z in Stata. Reparameterization imposes this fixed linear constraint; covariance reporting needs the corresponding coefficient transformation.
Stata reference · R reference
constraint define 1 x = z
L <- matrix(c(0,1,-1),nrow=1,dimnames=list(NULL,c("intercept","x","z")))
stats
Represent a linear equality constraint as a matrix
Fixed workflow: L beta = 0 encodes equal x and z coefficients. A fitting routine must enforce the constraint.
Stata reference · R reference
eivreg y x, reliability(x 0.8)
{ slope <- stats::cov(data$x,data$y)/(0.8*stats::var(data$x)); c(intercept=mean(data$y)-slope*mean(data$x),x=slope) }
stats
Correct a simple regression slope for known predictor reliability
Coefficient-only workflow for one error-prone predictor with known reliability and classical independent measurement error; no EIV standard errors are supplied.
Stata reference · R reference
fracreg logit share x
{ fit <- stats::glm(share ~ x,data=data,family=stats::quasibinomial(link="logit")); lmtest::coeftest(fit,vcov.=sandwich::vcovHC(fit,type="HC0"),df=Inf) }
sandwich
Fit fractional logit regression with sandwich inference
Differs from Stata: Quasi-binomial fit avoids a noninteger-success warning. Sandwich inference is explicit; finite-sample corrections can differ.
Stata reference · R reference
fracreg probit share x
{ fit <- stats::glm(share ~ x,data=data,family=stats::quasibinomial(link="probit")); lmtest::coeftest(fit,vcov.=sandwich::vcovHC(fit,type="HC0"),df=Inf) }
sandwich
Fit fractional probit regression with sandwich inference
Differs from Stata: Quasi-binomial fit avoids a noninteger-success warning. Sandwich inference is explicit; finite-sample corrections can differ.
Stata reference · R reference
glm b x z, family(binomial) link(cloglog)
stats::glm(b ~ x + z, data=data, family=stats::binomial(link="cloglog"))
stats
Fit a binomial complementary-log-log GLM
Differs from Stata: The family and link are explicit. R and Stata can use different dispersion scaling and reference tests even when fitted means agree; align the sample and scale option before comparing standard errors.
Stata reference · R reference
glm b x z, family(binomial) link(logit)
stats::glm(b ~ x + z, data=data, family=stats::binomial())
stats
Fit a binomial logit-link GLM
Differs from Stata: The family and link are explicit. R and Stata can use different dispersion scaling and reference tests even when fitted means agree; align the sample and scale option before comparing standard errors.
Stata reference · R reference
glm b x z, family(binomial) link(probit)
stats::glm(b ~ x + z, data=data, family=stats::binomial(link="probit"))
stats
Fit a binomial probit-link GLM
Differs from Stata: The family and link are explicit. R and Stata can use different dispersion scaling and reference tests even when fitted means agree; align the sample and scale option before comparing standard errors.
Stata reference · R reference
glm count x z, family(poisson) link(log)
stats::glm(count ~ x + z, data=data, family=stats::poisson())
stats
Fit a Poisson log-link GLM
Differs from Stata: The family and link are explicit. R and Stata can use different dispersion scaling and reference tests even when fitted means agree; align the sample and scale option before comparing standard errors.
Stata reference · R reference
glm count x, family(poisson) link(identity)
stats::glm(count ~ x, data=data, family=stats::poisson(link="identity"))
stats
Fit a Poisson identity-link GLM
Differs from Stata: The family and link are explicit. R and Stata can use different dispersion scaling and reference tests even when fitted means agree; align the sample and scale option before comparing standard errors.
Stata reference · R reference
glm events x, family(binomial trials) link(logit)
stats::glm(cbind(events,trials-events) ~ x,data=data,family=stats::binomial())
stats
Fit grouped-binomial events and trials
Differs from Stata: The family and link are explicit. R and Stata can use different dispersion scaling and reference tests even when fitted means agree; align the sample and scale option before comparing standard errors.
Stata reference · R reference
glm y x z, family(gamma) link(log)
stats::glm(y ~ x + z, data=data, family=stats::Gamma(link="log"))
stats
Fit a gamma log-link model for positive outcomes
Differs from Stata: The family and link are explicit. R and Stata can use different dispersion scaling and reference tests even when fitted means agree; align the sample and scale option before comparing standard errors.
Stata reference · R reference
glm y x z, family(gaussian) link(identity)
stats::glm(y ~ x + z, data=data, family=stats::gaussian())
stats
Fit a Gaussian identity-link GLM
Differs from Stata: The family and link are explicit. R and Stata can use different dispersion scaling and reference tests even when fitted means agree; align the sample and scale option before comparing standard errors.
Stata reference · R reference
glm y x z, family(gaussian) link(log)
stats::glm(y ~ x + z, data=data, family=stats::gaussian(link="log"))
stats
Fit a Gaussian log-link GLM
Differs from Stata: The family and link are explicit. R and Stata can use different dispersion scaling and reference tests even when fitted means agree; align the sample and scale option before comparing standard errors.
Stata reference · R reference
glm y x, family(gamma) link(identity)
stats::glm(y ~ x, data=data, family=stats::Gamma(link="identity"))
stats
Fit a gamma identity-link model
Differs from Stata: The family and link are explicit. R and Stata can use different dispersion scaling and reference tests even when fitted means agree; align the sample and scale option before comparing standard errors.
Stata reference · R reference
glm y x, family(gamma) link(inverse)
stats::glm(y ~ x, data=data, family=stats::Gamma(link="inverse"))
stats
Fit a gamma inverse-link model
Differs from Stata: The family and link are explicit. R and Stata can use different dispersion scaling and reference tests even when fitted means agree; align the sample and scale option before comparing standard errors.
Stata reference · R reference
glm y x, family(igaussian) link(identity)
stats::glm(y ~ x, data=data, family=stats::inverse.gaussian(link="identity"))
stats
Fit an inverse Gaussian identity-link model
Differs from Stata: The family and link are explicit. R and Stata can use different dispersion scaling and reference tests even when fitted means agree; align the sample and scale option before comparing standard errors.
Stata reference · R reference
glm y x, family(igaussian) link(log)
stats::glm(y ~ x, data=data, family=stats::inverse.gaussian(link="log"))
stats
Fit an inverse Gaussian log-link model
Differs from Stata: The family and link are explicit. R and Stata can use different dispersion scaling and reference tests even when fitted means agree; align the sample and scale option before comparing standard errors.
Stata reference · R reference
hetregress y x, het(z)
nlme::gls(y~x,data=data,weights=nlme::varExp(form=~z),method="ML")
nlme
Fit a normal mean model with multiplicative heteroskedasticity
Differs from Stata: nlme models SD as exp(theta*z), so the coefficient on z in Stata log variance is 2*theta.
Stata reference · R reference
intreg lower upper x z
survival::survreg(survival::Surv(lower,upper,type="interval2")~x+z,data=data,dist="gaussian")
survival
Fit normal regression to interval-valued outcomes
Differs from Stata: Uses survreg as a Gaussian interval-likelihood engine for a cross-sectional outcome, without a time-to-event interpretation.
Stata reference · R reference
iqreg y x z, quantiles(25 75)
{ fit <- quantreg::rq(y ~ x+z,data=data,tau=c(0.25,0.75)); stats::coef(fit)[,2]-stats::coef(fit)[,1] }
quantreg
Estimate slopes of the interquartile range
Coefficient workflow only; obtain standard errors by jointly resampling both quantile fits.
Stata reference · R reference
logistic b x z
{ fit <- stats::glm(b ~ x+z,data=data,family=stats::binomial()); exp(stats::coef(fit)) }
stats
Report logistic odds ratios
Differs from Stata: Exponentiates the binomial logit coefficients to odds ratios. Returns point estimates only, without the confidence intervals and tests printed by Stata logistic.
Stata reference · R reference
logit b x z
stats::glm(b ~ x + z,data=data,family=stats::binomial(link="logit"))
stats
Fit logit regression
Differs from Stata: R uses a binomial GLM with the logit link and returns coefficients on the log-odds scale. Match binary coding and complete cases; Stata iteration diagnostics and stored result structure differ.
Stata reference · R reference
logit b x z, noconstant
stats::glm(b ~ x + z - 1,data=data,family=stats::binomial(link="logit"))
stats
Fit logit without an intercept
Differs from Stata: R uses a binomial GLM with the logit link and returns coefficients on the log-odds scale. Match binary coding and complete cases; Stata iteration diagnostics and stored result structure differ.
Stata reference · R reference
mlexp (lnnormalden(y,{mu},exp({lnsigma})))
stats::optim(c(mu=mean(data$y),log_sigma=log(stats::sd(data$y))),function(par) -sum(stats::dnorm(data$y,mean=par[1],sd=exp(par[2]),log=TRUE)),method="BFGS",hessian=TRUE)
stats
Maximize an explicitly defined normal likelihood
Differs from Stata: R optimizes log sigma to enforce positivity; translate the scale parameter back using exp().
Stata reference · R reference
mlogit g x z, baseoutcome(4)
nnet::multinom(stats::relevel(factor(g), ref = "4") ~ x+z,data=data,trace=FALSE)
nnet
Fit multinomial logit with a chosen reference outcome
Differs from Stata: Relevels outcome category 4 to the first R factor level, matching baseoutcome(4). Coefficient labels and optimization criteria differ; keep the same observations and category support.
Stata reference · R reference
nbreg count x z
MASS::glm.nb(count ~ x+z,data=data)
MASS
Fit NB2 negative-binomial regression
Differs from Stata: Both use NB2 variance mu+alpha*mu^2; MASS theta is 1/alpha.
Stata reference · R reference
nl (y = {a=1} + {b=2}*x/({c=1}+x))
stats::nls(y ~ a+b*x/(c+x),data=data,start=list(a=1,b=2,c=1))
stats
Fit a nonlinear saturating response curve
Differs from Stata: Fits this explicit nonlinear mean function from the supplied starting values. nls and Stata nl use different convergence controls and can reach different local solutions.
Stata reference · R reference
nl (y = {a=2}*exp({b=0.2}*x))
stats::nls(y ~ a*exp(b*x),data=data,start=list(a=2,b=0.2))
stats
Fit a nonlinear exponential mean curve
Differs from Stata: Fits this explicit nonlinear mean function from the supplied starting values. nls and Stata nl use different convergence controls and can reach different local solutions.
Stata reference · R reference
ologit y x z
MASS::polr(y ~ x+z,data=data,method="logistic",Hess=TRUE)
MASS
Fit ordered ologit regression
Differs from Stata: MASS uses cumulative link intercepts; compare cutpoint and slope sign conventions.
Stata reference · R reference
oprobit y x z
MASS::polr(y ~ x+z,data=data,method="probit",Hess=TRUE)
MASS
Fit ordered oprobit regression
Differs from Stata: MASS uses cumulative link intercepts; compare cutpoint and slope sign conventions.
Stata reference · R reference
poisson count x z, exposure(exposure)
stats::glm(count ~ x+z+offset(log(exposure)),data=data,family=stats::poisson())
stats
Fit Poisson rates with exposure
Differs from Stata: Uses the explicit log offset where shown; exposure must be strictly positive. R returns a glm object or exponentiated coefficients, rather than the Stata estimation table; align overdispersion and robust variance options.
Stata reference · R reference
poisson count x z, irr
{ fit <- stats::glm(count~x+z,data=data,family=stats::poisson()); exp(stats::coef(fit)) }
stats
Report Poisson incidence-rate ratios
Differs from Stata: Uses the explicit log offset where shown; exposure must be strictly positive. R returns a glm object or exponentiated coefficients, rather than the Stata estimation table; align overdispersion and robust variance options.
Stata reference · R reference
poisson count x z, noconstant
stats::glm(count ~ x+z-1,data=data,family=stats::poisson())
stats
Fit Poisson regression without an intercept
Differs from Stata: Uses the explicit log offset where shown; exposure must be strictly positive. R returns a glm object or exponentiated coefficients, rather than the Stata estimation table; align overdispersion and robust variance options.
Stata reference · R reference
probit b x z
stats::glm(b ~ x + z,data=data,family=stats::binomial(link="probit"))
stats
Fit probit regression
Differs from Stata: R uses the probit binomial GLM. Match binary coding and complete cases; the GLM result object and convergence tolerances differ from Stata probit.
Stata reference · R reference
probit b x z, noconstant
stats::glm(b ~ x + z - 1,data=data,family=stats::binomial(link="probit"))
stats
Fit probit without an intercept
Differs from Stata: R uses the probit binomial GLM. Match binary coding and complete cases; the GLM result object and convergence tolerances differ from Stata probit.
Stata reference · R reference
qreg y x z, quantile(25)
quantreg::rq(y ~ x+z,data=data,tau=0.25)
quantreg
Fit conditional quantile 25 regression
Differs from Stata: Fits the selected conditional quantile. rq and Stata qreg use different optimization and default covariance estimators; coefficient agreement does not establish standard-error parity.
Stata reference · R reference
qreg y x z, quantile(75)
quantreg::rq(y ~ x+z,data=data,tau=0.75)
quantreg
Fit conditional quantile 75 regression
Differs from Stata: Fits the selected conditional quantile. rq and Stata qreg use different optimization and default covariance estimators; coefficient agreement does not establish standard-error parity.
Stata reference · R reference
regress y c.x##c.x
stats::lm(y ~ x + I(x^2), data=data)
stats
Fit a quadratic regression
Differs from Stata: OLS coefficient correspondence requires the same complete-case sample, contrasts and weights. R returns an lm object; Stata coefficient tables and stored estimates have a different structure.
Stata reference · R reference
regress y c.x##c.z
stats::lm(y ~ x * z, data=data)
stats
Include two continuous main effects and their interaction
Differs from Stata: OLS coefficient correspondence requires the same complete-case sample, contrasts and weights. R returns an lm object; Stata coefficient tables and stored estimates have a different structure.
Stata reference · R reference
regress y c.x##i.g
stats::lm(y ~ x * factor(g), data=data)
stats
Fit separate linear slopes by group
Differs from Stata: OLS coefficient correspondence requires the same complete-case sample, contrasts and weights. R returns an lm object; Stata coefficient tables and stored estimates have a different structure.
Stata reference · R reference
regress y i.g c.x
stats::lm(y ~ factor(g) + x, data=data)
stats
Adjust regression for a categorical predictor
Differs from Stata: OLS coefficient correspondence requires the same complete-case sample, contrasts and weights. R returns an lm object; Stata coefficient tables and stored estimates have a different structure.
Stata reference · R reference
regress y x [aweight=w]
stats::lm(y ~ x, data=data, weights=w)
stats
Fit analytic-weighted least squares
Differs from Stata: Weights are proportional inverse variances. Check scale and residual degrees of freedom before comparing software.
Stata reference · R reference
regress y x z if b == 1
stats::lm(y ~ x + z, data=data, subset=b == 1)
stats
Fit linear regression in a specified subgroup
Differs from Stata: OLS coefficient correspondence requires the same complete-case sample, contrasts and weights. R returns an lm object; Stata coefficient tables and stored estimates have a different structure.
Stata reference · R reference
regress y x z, beta
{ fit <- stats::lm(y ~ x + z, data=data); stats::coef(fit)[c("x","z")] * vapply(data[c("x","z")], stats::sd, numeric(1)) / stats::sd(data$y) }
stats
Report standardized linear regression slopes
Differs from Stata: OLS coefficient correspondence requires the same complete-case sample, contrasts and weights. R returns an lm object; Stata coefficient tables and stored estimates have a different structure.
Stata reference · R reference
regress y x z, noconstant
stats::lm(y ~ x + z - 1, data=data)
stats
Fit linear regression through the origin
Differs from Stata: OLS coefficient correspondence requires the same complete-case sample, contrasts and weights. R returns an lm object; Stata coefficient tables and stored estimates have a different structure.
Stata reference · R reference
regress y x z, vce(cluster g)
{ fit <- stats::lm(y ~ x + z, data = data, subset = !is.na(g)); lmtest::coeftest(fit, vcov. = sandwich::vcovCL(fit, cluster = ~g, type = "HC1"), df = length(unique(stats::expand.model.frame(fit, ~g)$g)) - 1L) }
sandwich
Use one-way clustered standard errors with cluster degrees of freedom
Differs from Stata: Only three clusters in this demonstration fixture; substantive applications need adequate independent clusters.
Stata reference · R reference
regress y x z, vce(hc2)
{ fit <- stats::lm(y~x+z,data=data); lmtest::coeftest(fit, vcov.=sandwich::vcovHC(fit,type="HC2")) }
sandwich
Report HC2 heteroskedasticity-robust OLS inference
Differs from Stata: Coefficient estimates are OLS; covariance correction is selected explicitly.
Stata reference · R reference
regress y x z, vce(hc3)
{ fit <- stats::lm(y~x+z,data=data); lmtest::coeftest(fit, vcov.=sandwich::vcovHC(fit,type="HC3")) }
sandwich
Report HC3 heteroskedasticity-robust OLS inference
Differs from Stata: Coefficient estimates are OLS; covariance correction is selected explicitly.
Stata reference · R reference
regress y x z, vce(robust)
{ fit <- stats::lm(y~x+z,data=data); lmtest::coeftest(fit, vcov.=sandwich::vcovHC(fit,type="HC1")) }
sandwich
Report HC1 heteroskedasticity-robust OLS inference
Differs from Stata: Coefficient estimates are OLS; covariance correction is selected explicitly.
Stata reference · R reference
rreg y x z
MASS::rlm(y ~ x+z,data=data,psi=MASS::psi.bisquare,init="lts",maxit=100)
MASS
Fit a resistant bisquare regression
Workflow equivalent: Stata rreg uses its own screening and iteration sequence, so coefficients need not match.
Stata reference · R reference
sqreg y x z, quantiles(25 50 75)
quantreg::rq(y ~ x+z,data=data,tau=c(0.25,0.5,0.75))
quantreg
Fit several conditional quantiles together
This fits coefficients; Stata sqreg also bootstraps their joint covariance. Use a shared-resample bootstrap for joint inference.
Stata reference · R reference
tobit y x z, ll(0)
AER::tobit(y~x+z,data=data,left=0)
AER
Fit a left-censored normal Tobit model
Differs from Stata: Uses the explicit left and/or right censoring limits. AER returns a survreg-based Gaussian censored model; scale parameter reporting and coefficient-table inference differ from Stata.
Stata reference · R reference
tobit y x z, ll(0) ul(2)
AER::tobit(y~x+z,data=data,left=0,right=2)
AER
Fit a two-limit censored normal model
Differs from Stata: Uses the explicit left and/or right censoring limits. AER returns a survreg-based Gaussian censored model; scale parameter reporting and coefficient-table inference differ from Stata.
Stata reference · R reference
tobit y x z, ul(2)
AER::tobit(y~x+z,data=data,left=-Inf,right=2)
AER
Fit a right-censored normal Tobit model
Differs from Stata: Uses the explicit left and/or right censoring limits. AER returns a survreg-based Gaussian censored model; scale parameter reporting and coefficient-table inference differ from Stata.
Stata reference · R reference
zinb count x, inflate(z)
pscl::zeroinfl(count~x|z,data=data,dist="negbin",link="logit")
pscl
Fit a zero-inflated NB2 count model
Differs from Stata: Negative-binomial theta is reciprocal to Stata alpha in the NB2 component.
Stata reference · R reference
zip count x, inflate(z)
pscl::zeroinfl(count~x|z,data=data,dist="poisson",link="logit")
pscl
Fit zero-inflated Poisson with logit zero inflation
Differs from Stata: Fits the stated zero-inflated Poisson model with separate count and inflation equations. Match the inflation link, offsets and complete cases; optimizers and coefficient labels differ.
Stata reference · R reference
zip count x, inflate(z) probit
pscl::zeroinfl(count~x|z,data=data,dist="poisson",link="probit")
pscl
Fit zero-inflated Poisson with probit zero inflation
Differs from Stata: Fits the stated zero-inflated Poisson model with separate count and inflation equations. Match the inflation link, offsets and complete cases; optimizers and coefficient labels differ.
Stata reference · R reference

Postestimation and diagnostics

Stata R Purpose, qualifications and sources
brier b p
mean((data$b-data$p)^2)
stats
Calculate the overall Brier mean probability score
Differs from Stata: Returns the overall score only; Stata brier also reports decomposition components.
Stata reference · R reference
dfbeta x
stats::dfbetas(fit)[,"x"]
stats
Obtain standardized deletion influence on one slope
Differs from Stata: Returns standardized coefficient-deletion diagnostics from dfbetas for x; coefficient ordering, missing rows and diagnostic naming must be aligned with the Stata model.
Stata reference · R reference
estat hettest x, iid
lmtest::bptest(fit,varformula=~x,data=data,studentize=TRUE)
lmtest
Test heteroskedasticity against one predictor using a studentized statistic
Differs from Stata: Uses the studentized Koenker version of the Breusch-Pagan test, corresponding to the iid variant shown. Match the auxiliary regressors and estimation sample; the default bptest differs from default Stata hettest.
Stata reference · R reference
estat hettest, rhs
lmtest::bptest(fit,studentize=FALSE)
lmtest
Run the classical Breusch-Pagan heteroskedasticity test
Differs from Stata: studentize=FALSE selects the normal-theory version; default bptest uses the Koenker version.
Stata reference · R reference
estat ic
c(AIC=stats::AIC(fit),BIC=stats::BIC(fit))
stats
Compare penalized-likelihood model criteria
R keeps fitted model objects; model names are fixed workflow labels.
Stata reference · R reference
estat imtest, white
lmtest::bptest(fit,varformula=~x+z+I(x^2)+I(z^2)+x:z,data=data,studentize=TRUE)
lmtest
Run a White-style auxiliary-regression heteroskedasticity test
This covers the White heteroskedasticity component, not the complete information-matrix decomposition.
Stata reference · R reference
estat ovtest
lmtest::resettest(fit,power=2:4,type="fitted")
lmtest
Run Ramsey RESET using powers of fitted values
Differs from Stata: Uses RESET powers two through four of the fitted values or regressors as shown. Regressor-factor expansion and rank-deficient auxiliary terms may differ from Stata.
Stata reference · R reference
estat ovtest, rhs
lmtest::resettest(fit,power=2:4,type="regressor")
lmtest
Run RESET using powers of regressors
Differs from Stata: Uses RESET powers two through four of the fitted values or regressors as shown. Regressor-factor expansion and rank-deficient auxiliary terms may differ from Stata.
Stata reference · R reference
estat summarize
summary(stats::model.frame(fit))
stats
Summarize variables in the actual estimation sample
R keeps fitted model objects; model names are fixed workflow labels.
Stata reference · R reference
estat vce
stats::vcov(fit)
stats
Extract the coefficient covariance matrix
R keeps fitted model objects; model names are fixed workflow labels.
Stata reference · R reference
estat vce, correlation
stats::cov2cor(stats::vcov(fit))
stats
Extract correlations among coefficient estimates
R keeps fitted model objects; model names are fixed workflow labels.
Stata reference · R reference
estat vif
car::vif(fit)
car
Compute variance inflation factors after OLS
Differs from Stata: car returns ordinary VIFs for one-degree-of-freedom terms and generalized VIFs for multi-parameter terms. Stata estat vif reports column-level VIFs, so factor-term output is not directly interchangeable.
Stata reference · R reference
estimates dir
names(models)
stats
List stored model names
R keeps fitted model objects; model names are fixed workflow labels.
Stata reference · R reference
estimates replay
summary(fit)
stats
Redisplay a fitted linear model summary
R keeps fitted model objects; model names are fixed workflow labels.
Stata reference · R reference
estimates restore model1
fit <- models[["model1"]]
stats
Restore one model from a model collection
R keeps fitted model objects; model names are fixed workflow labels.
Stata reference · R reference
estimates save model1
{ path <- tempfile(fileext=".rds"); saveRDS(fit,path); readRDS(path) }
base
Save and reload a fitted model object
Writes to an R temporary file; choose an explicit project path for persistent storage.
Stata reference · R reference
estimates stats model1 model2
do.call(stats::AIC,unname(models))
stats
Compare AIC across stored model objects
R keeps fitted model objects; model names are fixed workflow labels.
Stata reference · R reference
estimates store model1
model1 <- fit
stats
Store a fitted model under a name
R keeps fitted model objects; model names are fixed workflow labels.
Stata reference · R reference
estimates table model1 model2, b se
lapply(models,function(m) summary(m)$coefficients[,1:2,drop=FALSE])
stats
Compare coefficients and standard errors across models
R keeps fitted model objects; model names are fixed workflow labels.
Stata reference · R reference
lincom x + z
{ L <- c(0,1,1); c(estimate=sum(L*stats::coef(fit)),se=sqrt(drop(t(L)%*%stats::vcov(fit)%*%L))) }
stats
Estimate the sum of two slopes with its standard error
Differs from Stata: The contrast vector assumes coefficient order intercept, x, z. Returns the estimate and its covariance-based standard error only; Stata also prints tests and confidence limits.
Stata reference · R reference
lincom x - z
{ L <- c(0,1,-1); c(estimate=sum(L*stats::coef(fit)),se=sqrt(drop(t(L)%*%stats::vcov(fit)%*%L))) }
stats
Estimate a difference of slopes with its standard error
Differs from Stata: The contrast vector assumes coefficient order intercept, x, z. Returns the estimate and its covariance-based standard error only; Stata also prints tests and confidence limits.
Stata reference · R reference
linktest
{ data$hat <- stats::fitted(fit); stats::lm(y ~ hat+I(hat^2),data=data) }
stats
Regress an outcome on fitted values and their square
Shown for OLS; link tests after other model families must refit the appropriate family.
Stata reference · R reference
lrtest reduced full
lmtest::lrtest(reduced,full)
lmtest
Compare nested maximum-likelihood models
Differs from Stata: Fixed workflow.
Stata reference · R reference
margins, at(x=(2 3 4))
vapply(c(2,3,4),function(value) { newdata <- data; newdata$x <- value; mean(stats::predict(fit,newdata=newdata,type="response")) },numeric(1))
stats
Predict at specified covariate values
Differs from Stata: At each x value, predictions are averaged over the observed distribution of z.
Stata reference · R reference
margins, dydx(x)
{ X <- stats::model.matrix(fit); beta <- stats::coef(fit); p <- stats::fitted(fit); gradient <- beta["x"]*colMeans(X*as.vector(p*(1-p)*(1-2*p))); gradient["x"] <- gradient["x"]+mean(p*(1-p)); c(estimate=unname(beta["x"]*mean(p*(1-p))),se=sqrt(drop(t(gradient)%*%stats::vcov(fit)%*%gradient))) }
stats
Average a continuous-predictor marginal effect
Differs from Stata: Uses the fitted GLM and its estimation data; reference grids and averaging rules should be chosen explicitly.
Stata reference · R reference
margins, dydx(x) atmeans
{ X <- colMeans(stats::model.matrix(fit)); beta <- stats::coef(fit); p <- stats::plogis(sum(X*beta)); c(estimate=unname(beta["x"]*p*(1-p))) }
stats
Evaluate a marginal effect at mean covariates
Differs from Stata: Returns the derivative at means; use a delta-method gradient if standard errors are needed.
Stata reference · R reference
margins, expression(predict(xb))
{ L <- colMeans(stats::model.matrix(fit)); c(estimate=sum(L*stats::coef(fit)),se=sqrt(drop(t(L)%*%stats::vcov(fit)%*%L))) }
stats
Average predictions on the linear-index scale
Differs from Stata: Uses the fitted GLM and its estimation data; reference grids and averaging rules should be chosen explicitly.
Stata reference · R reference
nlcom _b[x]/_b[z]
car::deltaMethod(fit,"x / z")
car
Use the delta method for a ratio of slopes
Differs from Stata: Uses the first-order delta method on named fitted coefficients. Returns the transformed estimate and standard error; Stata also prints reference tests and confidence limits.
Stata reference · R reference
nlcom exp(_b[x])
car::deltaMethod(fit,"exp(x)")
car
Use the delta method for an exponentiated slope
Differs from Stata: Uses the first-order delta method on named fitted coefficients. Returns the transformed estimate and standard error; Stata also prints reference tests and confidence limits.
Stata reference · R reference
predict result, cooksd
data$result <- stats::cooks.distance(fit)
stats
Obtain Cook influence distances
Differs from Stata: Run after fit <- lm(y ~ x + z, data=data).
Stata reference · R reference
predict result, deviance
data$result <- stats::residuals(fit,type="deviance")
stats
Compute binary-model deviance residuals
Differs from Stata: After fitting a binary-response GLM. Prediction options are model-specific.
Stata reference · R reference
predict result, dfits
data$result <- stats::dffits(fit)
stats
Obtain DFFITS influence statistics
Differs from Stata: Run after fit <- lm(y ~ x + z, data=data).
Stata reference · R reference
predict result, hat
data$result <- stats::hatvalues(fit)
stats
Obtain leverage values
Differs from Stata: Run after fit <- lm(y ~ x + z, data=data).
Stata reference · R reference
predict result, pearson
data$result <- stats::residuals(fit,type="pearson")
stats
Compute binary-model Pearson residuals
Differs from Stata: After fitting a binary-response GLM. Prediction options are model-specific.
Stata reference · R reference
predict result, pr
data$result <- stats::predict(fit,type="response")
stats
Predict logistic probabilities
Differs from Stata: After fitting a binary-response GLM. Prediction options are model-specific.
Stata reference · R reference
predict result, residuals
data$result <- stats::residuals(fit)
stats
Obtain raw OLS residuals
Differs from Stata: Run after fit <- lm(y ~ x + z, data=data).
Stata reference · R reference
predict result, rstandard
data$result <- stats::rstandard(fit)
stats
Obtain internally standardized residuals
Differs from Stata: Run after fit <- lm(y ~ x + z, data=data).
Stata reference · R reference
predict result, rstudent
data$result <- stats::rstudent(fit)
stats
Obtain externally studentized residuals
Differs from Stata: Run after fit <- lm(y ~ x + z, data=data).
Stata reference · R reference
predict result, stdf
data$result <- sqrt(stats::predict(fit,se.fit=TRUE)$se.fit^2+summary(fit)$sigma^2)
stats
Obtain forecast standard errors including residual variance
Differs from Stata: Adds residual variance to the squared standard error of the fitted OLS mean. This is a standard error for a new individual prediction, not the fitted mean; assumes homoskedastic errors and matching model sample.
Stata reference · R reference
predict result, stdp
data$result <- stats::predict(fit,se.fit=TRUE)$se.fit
stats
Obtain standard errors of fitted means
Differs from Stata: Run after fit <- lm(y ~ x + z, data=data).
Stata reference · R reference
predict result, xb
data$result <- stats::predict(fit)
stats
Obtain linear fitted values
Differs from Stata: Run after fit <- lm(y ~ x + z, data=data).
Stata reference · R reference
predict result, xb
data$result <- stats::predict(fit,type="link")
stats
Predict logistic linear indices
Differs from Stata: After fitting a binary-response GLM. Prediction options are model-specific.
Stata reference · R reference
roccomp b x z
pROC::roc.test(pROC::roc(data$b,data$x,levels=c(0,1),direction="<",quiet=TRUE),pROC::roc(data$b,data$z,levels=c(0,1),direction="<",quiet=TRUE),paired=TRUE,method="delong")
pROC
Compare paired marker ROC areas using DeLong inference
Differs from Stata: Both markers must be measured on the same complete-case subjects for paired inference.
Stata reference · R reference
roctab b x
pROC::roc(data$b,data$x,levels=c(0,1),direction="<",quiet=TRUE)
pROC
Estimate a nonparametric ROC area for a marker
Differs from Stata: Explicit direction means larger markers indicate cases; fixing direction prevents data-driven reversal.
Stata reference · R reference
roctab b x, detail
pROC::coords(pROC::roc(data$b,data$x,levels=c(0,1),direction="<",quiet=TRUE),x="all",ret=c("threshold","sensitivity","specificity"))
pROC
Tabulate sensitivity and specificity across ROC thresholds
Differs from Stata: Returns all pROC thresholds with sensitivity and specificity for explicit event direction. Threshold locations and endpoint conventions differ from Stata roctab detail cutpoints.
Stata reference · R reference
test x = 0
car::linearHypothesis(fit,"x = 0")
car
Test a single regression coefficient
Differs from Stata: Tests the specified coefficient restriction on the existing fit. car selects its reference statistic from the model class; a GLM chi-square test differs from the OLS F test used by Stata regress postestimation.
Stata reference · R reference
test x = z
car::linearHypothesis(fit,"x = z")
car
Test equality of two regression slopes
Differs from Stata: Tests the specified coefficient restriction on the existing fit. car selects its reference statistic from the model class; a GLM chi-square test differs from the OLS F test used by Stata regress postestimation.
Stata reference · R reference
test x z
car::linearHypothesis(fit,c("x = 0","z = 0"))
car
Jointly test two regression coefficients
Differs from Stata: Tests the specified coefficient restriction on the existing fit. car selects its reference statistic from the model class; a GLM chi-square test differs from the OLS F test used by Stata regress postestimation.
Stata reference · R reference
testnl exp(_b[x]) = 1
{ d <- car::deltaMethod(fit,"exp(x)"); w <- ((d$Estimate-1)/d$SE)^2; c(chisq=w,p.value=stats::pchisq(w,df=1,lower.tail=FALSE)) }
car
Test an exponentiated coefficient with a nonlinear Wald test
Differs from Stata: Forms a one-degree-of-freedom Wald chi-square from a first-order delta-method standard error. The R vector omits Stata coefficient and confidence-interval output.
Stata reference · R reference
testparm i.g
car::linearHypothesis(fit,c("g6 = 0","g8 = 0"))
car
Jointly test a categorical predictor
Differs from Stata: The restrictions name the fitted factor coefficients explicitly. Different reference levels or contrasts require different coefficient names; this is not an automatic expansion of any Stata factor-variable expression.
Stata reference · R reference

Hypothesis tests and confidence intervals

Stata R Purpose, qualifications and sources
bitest b = 0.5
stats::binom.test(sum(data$b),nrow(data),p=0.5)
stats
Test a binary success probability exactly
Differs from Stata: Returns an exact two-sided binomial test. The code assumes the displayed binary sample has no missing values; Stata additionally prints lower- and upper-tail probabilities.
Stata reference · R reference
bitesti 20 7 0.5
stats::binom.test(7,20,p=0.5)
stats
Run an exact binomial test from counts
Differs from Stata: Uses an exact two-sided binomial test from the supplied count and total. R reports one htest result; Stata additionally displays both one-sided probabilities.
Stata reference · R reference
ci means y
stats::t.test(data$y)$conf.int
stats
Compute a Student-t confidence interval for a mean
Differs from Stata: Returns only the selected confidence limits, not Stata sample-size and point-estimate columns. Match nonmissing sample size, confidence level and the explicit interval method.
Stata reference · R reference
ci proportions b, exact
stats::binom.test(sum(data$b),nrow(data))$conf.int
stats
Compute a Clopper-Pearson proportion interval
Differs from Stata: Returns only the selected confidence limits, not Stata sample-size and point-estimate columns. Match nonmissing sample size, confidence level and the explicit interval method.
Stata reference · R reference
ci proportions b, wilson
stats::prop.test(sum(data$b),nrow(data),correct=FALSE)$conf.int
stats
Compute a Wilson score interval for a proportion
Differs from Stata: Returns only the selected confidence limits, not Stata sample-size and point-estimate columns. Match nonmissing sample size, confidence level and the explicit interval method.
Stata reference · R reference
ci variances y
(length(data$y)-1)*stats::var(data$y)/stats::qchisq(c(0.975,0.025),df=length(data$y)-1)
stats
Compute a normal-theory variance interval
Differs from Stata: Returns only the selected confidence limits, not Stata sample-size and point-estimate columns. Match nonmissing sample size, confidence level and the explicit interval method.
Stata reference · R reference
ci variances y, sd
sqrt((length(data$y)-1)*stats::var(data$y)/stats::qchisq(c(0.975,0.025),df=length(data$y)-1))
stats
Compute a normal-theory standard-deviation interval
Differs from Stata: Returns only the selected confidence limits, not Stata sample-size and point-estimate columns. Match nonmissing sample size, confidence level and the explicit interval method.
Stata reference · R reference
cii means 50 10 2
10+c(-1,1)*stats::qt(0.975,49)*2/sqrt(50)
stats
Compute a mean interval from summary statistics
Differs from Stata: Computes confidence limits from the displayed summary inputs. The R result omits Stata sample-size and point-estimate columns; the stated method and confidence level determine the interval.
Stata reference · R reference
cii proportions 20 7, exact
stats::binom.test(7,20)$conf.int
stats
Compute an exact proportion interval from counts
Differs from Stata: Computes confidence limits from the displayed summary inputs. The R result omits Stata sample-size and point-estimate columns; the stated method and confidence level determine the interval.
Stata reference · R reference
ksmirnov y, by(g)
stats::ks.test(data$y[data$g=="a"],data$y[data$g=="b"],exact=FALSE)
stats
Compare two empirical distribution functions
Differs from Stata: The two-sample form uses a grouping variable; a one-sample test instead requires a fully specified reference CDF.
Stata reference · R reference
ktau y x
stats::cor.test(data$y,data$x,method="kendall",exact=FALSE)
stats
Test Kendall rank association
Differs from Stata: Uses the asymptotic Kendall test. Tie adjustments and the reported tau variant must match; R returns one htest object rather than Stata full concordance summaries.
Stata reference · R reference
kwallis y, by(g)
stats::kruskal.test(y~g,data=data)
stats
Test equality of distributions across groups
Differs from Stata: Computes the tie-corrected Kruskal-Wallis chi-square approximation. R returns an htest object without Stata group rank-sum summaries.
Stata reference · R reference
median y, by(g)
stats::chisq.test(table(data$g,data$y>stats::median(data$y)),correct=FALSE)
stats
Run a two-group median test
Differs from Stata: Tests independence of group and the above-pooled-median indicator. The example assigns observations tied at the median to the lower category; align Stata ties() handling before comparison.
Stata reference · R reference
nptrend b, group(g) carmitage
stats::prop.trend.test(c(10,18,28),c(40,40,40),score=c(1,2,3))
stats
Test an ordered trend in proportions
Differs from Stata: Illustrates aggregated successes and denominators at the three ordered group scores.
Stata reference · R reference
oneway y g, bonferroni
stats::pairwise.t.test(data$y,data$g,p.adjust.method="bonferroni",pool.sd=TRUE)
stats
Compare group means with Bonferroni adjustment
Differs from Stata: Uses the ordinary equal-variance one-way model or pooled pairwise t tests as shown. R object layout differs and does not reproduce every Stata tabulate column or comparison display.
Stata reference · R reference
oneway y g, tabulate
stats::aov(y~factor(g),data=data)
stats
Fit one-way analysis of variance
Differs from Stata: Uses the ordinary equal-variance one-way model or pooled pairwise t tests as shown. R object layout differs and does not reproduce every Stata tabulate column or comparison display.
Stata reference · R reference
pcorr y x z
stats::cor(stats::residuals(stats::lm(y~z,data=data)),stats::residuals(stats::lm(x~z,data=data)))
stats
Compute the partial correlation of y and x controlling z
Differs from Stata: This returns the y-x partial correlation; Stata pcorr also reports semipartial correlations for each listed predictor.
Stata reference · R reference
prtest b == 0.5
stats::prop.test(sum(data$b),nrow(data),p=0.5,correct=FALSE)
stats
Run an uncorrected large-sample one-proportion test
Differs from Stata: Disables the R continuity correction for the normal-approximation proportion test. R reports a chi-square statistic whose square root is the absolute Stata z; signed direction requires the group order.
Stata reference · R reference
prtest b, by(g)
stats::prop.test(tapply(data$b,data$g,sum),as.vector(table(data$g)),correct=FALSE)
stats
Compare two proportions without continuity correction
Differs from Stata: Disables the R continuity correction for the normal-approximation proportion test. R reports a chi-square statistic whose square root is the absolute Stata z; signed direction requires the group order.
Stata reference · R reference
prtesti 100 0.4 120 0.5
stats::prop.test(c(40,60),c(100,120),correct=FALSE)
stats
Compare proportions from aggregate sample sizes
Differs from Stata: Disables continuity correction. R returns a chi-square test; Stata reports a signed z and one-sided probabilities, although the two-sided p-values correspond for the same counts.
Stata reference · R reference
ranksum y, by(g)
stats::wilcox.test(y~g,data=data,exact=FALSE,correct=FALSE)
stats
Compare independent distributions with the rank-sum test
Differs from Stata: Aligns the requested exact or uncorrected asymptotic Wilcoxon calculation. Tie handling, group ordering and reported rank-sum versus U-statistic conventions must be aligned.
Stata reference · R reference
ranksum y, by(g) exact
stats::wilcox.test(y~g,data=data,exact=TRUE)
stats
Use exact rank-sum inference without ties
Differs from Stata: Aligns the requested exact or uncorrected asymptotic Wilcoxon calculation. Tie handling, group ordering and reported rank-sum versus U-statistic conventions must be aligned.
Stata reference · R reference
sdtest y == 3
{ statistic <- (length(data$y)-1)*stats::var(data$y)/3^2; c(chisq=statistic,p.value=2*min(stats::pchisq(statistic,11),stats::pchisq(statistic,11,lower.tail=FALSE))) }
stats
Test one normal population standard deviation
Differs from Stata: Uses a normal-theory variance-ratio or chi-square test. R returns test components in an htest object or vector; Stata also reports one-sided alternatives and additional confidence limits.
Stata reference · R reference
sdtest y == x
stats::var.test(data$y,data$x)
stats
Compare two unpaired sample variances
Differs from Stata: Uses a normal-theory variance-ratio or chi-square test. R returns test components in an htest object or vector; Stata also reports one-sided alternatives and additional confidence limits.
Stata reference · R reference
sdtest y, by(g)
stats::var.test(y~g,data=data)
stats
Compare variances of two independent normal samples
Differs from Stata: Uses a normal-theory variance-ratio or chi-square test. R returns test components in an htest object or vector; Stata also reports one-sided alternatives and additional confidence limits.
Stata reference · R reference
sdtesti 30 2 40 3
{ f <- 2^2/3^2; c(F=f,p.value=2*min(stats::pf(f,29,39),stats::pf(f,29,39,lower.tail=FALSE))) }
stats
Compare variances from sample sizes and standard deviations
Differs from Stata: Computes the two-sided normal-theory variance-ratio test from the supplied summaries. The R vector omits Stata confidence intervals and one-sided probability columns.
Stata reference · R reference
signrank y = x
stats::wilcox.test(data$y,data$x,paired=TRUE,exact=FALSE,correct=FALSE)
stats
Use a paired signed-rank test with ties
Differs from Stata: Uses the paired Wilcoxon asymptotic calculation without continuity correction. R omits zero differences; ties and small-sample variance conventions can affect the reference approximation.
Stata reference · R reference
signtest y = x
{ d <- data$y-data$x; stats::binom.test(sum(d>0),sum(d!=0),p=0.5) }
stats
Test the median paired difference using signs
Differs from Stata: Drops zero paired differences and applies an exact two-sided binomial test. The displayed R interval concerns the probability of a positive difference, not a confidence interval for the paired median.
Stata reference · R reference
spearman y x
stats::cor.test(data$y,data$x,method="spearman",exact=FALSE)
stats
Test Spearman rank association with ties
Differs from Stata: Uses the asymptotic Spearman test explicitly. R and Stata p-value approximations can differ, especially with ties; compare the rank correlation on the same complete pairs.
Stata reference · R reference
swilk y
stats::shapiro.test(data$y)
stats
Test univariate normality with Shapiro-Wilk
Differs from Stata: Computes the Shapiro-Wilk W test; R permits 3 to 5000 nonmissing observations. Stata also displays transformed statistics and uses its own approximation and sample-size rules.
Stata reference · R reference
symmetry rater1 rater2
stats::mcnemar.test(table(data$rater1,data$rater2),correct=FALSE)
stats
Test symmetry in a matched binary table
Differs from Stata: For a 2 by 2 table this is the uncorrected McNemar test; larger-table symmetry needs a different procedure.
Stata reference · R reference
tabi 12 8 \ 5 15, chi2
stats::chisq.test(matrix(c(12,8,5,15),nrow=2,byrow=TRUE),correct=FALSE)
stats
Run a Pearson test from immediate cell counts
Differs from Stata: Builds the stated table by rows and disables continuity correction for Pearson chi-square. R returns an htest object rather than Stata contingency-table output.
Stata reference · R reference
tabulate g b, chi2
stats::chisq.test(table(data$g,data$b),correct=FALSE)
stats
Test association in a two-way count table
Differs from Stata: table excludes missing observations and unused factor levels can affect dimensions. The R htest object provides the selected Pearson or Fisher test without Stata row and column percentage displays.
Stata reference · R reference
tabulate g b, exact
stats::fisher.test(table(data$g,data$b))
stats
Run a Fisher exact test for a two-way table
Differs from Stata: table excludes missing observations and unused factor levels can affect dimensions. The R htest object provides the selected Pearson or Fisher test without Stata row and column percentage displays.
Stata reference · R reference
ttest y == 8
stats::t.test(data$y,mu=8)
stats
Test a mean against a specified value
Differs from Stata: Selects pooled, Welch or paired inference explicitly. R returns an htest object and may reverse the reported difference when factor-level order differs; match group order and the nonmissing sample.
Stata reference · R reference
ttest y == 8, level(90)
stats::t.test(data$y,mu=8,conf.level=0.90)
stats
Compute a 90 percent interval for a mean
Differs from Stata: Selects pooled, Welch or paired inference explicitly. R returns an htest object and may reverse the reported difference when factor-level order differs; match group order and the nonmissing sample.
Stata reference · R reference
ttest y == x
stats::t.test(data$y,data$x,paired=TRUE)
stats
Test paired mean differences
Differs from Stata: Selects pooled, Welch or paired inference explicitly. R returns an htest object and may reverse the reported difference when factor-level order differs; match group order and the nonmissing sample.
Stata reference · R reference
ttest y, by(g)
stats::t.test(y~g,data=data,var.equal=TRUE)
stats
Compare two independent means with pooled variance
Differs from Stata: Selects pooled, Welch or paired inference explicitly. R returns an htest object and may reverse the reported difference when factor-level order differs; match group order and the nonmissing sample.
Stata reference · R reference
ttest y, by(g) unequal
stats::t.test(y~g,data=data,var.equal=FALSE)
stats
Compare two means using Welch unequal-variance inference
Differs from Stata: Selects pooled, Welch or paired inference explicitly. R returns an htest object and may reverse the reported difference when factor-level order differs; match group order and the nonmissing sample.
Stata reference · R reference
ttesti 30 10 2 8
{ t <- (10-8)/(2/sqrt(30)); c(t=t,df=29,p.value=2*stats::pt(-abs(t),29)) }
stats
Run a one-mean t test from summary statistics
Differs from Stata: Computes the one-sample t statistic, degrees of freedom and two-sided p-value from the supplied summaries. The R vector omits the confidence interval and one-sided probabilities.
Stata reference · R reference

Multivariate and psychometric methods

Stata R Purpose, qualifications and sources
alpha q1 q2 q3, asis
psych::alpha(data[c("q1","q2","q3")],check.keys=FALSE)
psych
Estimate raw Cronbach alpha without reversing items
Differs from Stata: asis disables Stata item-direction reversal; check.keys=FALSE makes the R direction rule explicit.
Stata reference · R reference
alpha q1 q2 q3, generate(score) asis
score <- rowMeans(data[c("q1","q2","q3")])
base
Generate a mean score from a reliability scale
Differs from Stata: asis disables Stata item-direction reversal; check.keys=FALSE makes the R direction rule explicit.
Stata reference · R reference
alpha q1 q2 q3, item asis
psych::alpha(data[c("q1","q2","q3")],check.keys=FALSE)$alpha.drop
psych
Assess reliability when each item is deleted
Differs from Stata: asis disables Stata item-direction reversal; check.keys=FALSE makes the R direction rule explicit.
Stata reference · R reference
alpha q1 q2 q3, std asis
psych::alpha(data[c("q1","q2","q3")],check.keys=FALSE)$total$std.alpha
psych
Estimate standardized Cronbach alpha
Differs from Stata: asis disables Stata item-direction reversal; check.keys=FALSE makes the R direction rule explicit.
Stata reference · R reference
ca g h
MASS::corresp(unclass(table(data$g,data$h)),nf=2)
MASS
Perform simple correspondence analysis of a contingency table
Differs from Stata: MASS returns standard coordinates; Stata ca defaults to normalize(symmetric), so plotted coordinates differ in scale. Singular values and inertias are comparable, while axes may reverse signs. The table retains category names.
Stata reference · R reference
camat C, dimensions(2)
MASS::corresp(C,nf=2)
MASS
Perform correspondence analysis of a supplied count matrix
Differs from Stata: MASS returns standard correspondence coordinates; Stata defaults to symmetric normalization. Singular values are comparable, but coordinate scaling and axis signs can differ.
Stata reference · R reference
candisc x y z w, group(g)
MASS::lda(g ~ x+y+z+w,data=data,prior=rep(1/3,3))
MASS
Estimate canonical linear discriminant directions
Differs from Stata: MASS lda supplies discriminant directions with equal class priors. This is a discriminant-analysis workflow, not the full Stata candisc canonical-test and normalization output.
Stata reference · R reference
canon (x y) (z w)
stats::cancor(data[c("x","y")],data[c("z","w")])
stats
Estimate canonical correlations between two variable sets
Differs from Stata: Returns canonical correlations and coefficient matrices for the two variable blocks. Canonical signs and coefficient normalization are arbitrary; Stata also reports significance tests.
Stata reference · R reference
cluster averagelinkage x y z w
stats::hclust(stats::dist(scale(as.matrix(data[c("x","y","z","w")]))),method="average")
stats
Fit averagelinkage hierarchical clustering on standardized variables
Differs from Stata: Standardize variables before the analogous Stata call. Ward distance and squaring conventions require care.
Stata reference · R reference
cluster centroidlinkage x y z w
stats::hclust(stats::dist(scale(as.matrix(data[c("x","y","z","w")]))),method="centroid")
stats
Fit centroidlinkage hierarchical clustering on standardized variables
Differs from Stata: Standardize variables before the analogous Stata call. Ward distance and squaring conventions require care.
Stata reference · R reference
cluster completelinkage x y z w
stats::hclust(stats::dist(scale(as.matrix(data[c("x","y","z","w")]))),method="complete")
stats
Fit completelinkage hierarchical clustering on standardized variables
Differs from Stata: Standardize variables before the analogous Stata call. Ward distance and squaring conventions require care.
Stata reference · R reference
cluster generate group = groups(3)
stats::cutree(fit,k=3)
stats
Cut a hierarchical cluster tree into three groups
Differs from Stata: Cuts the existing hclust tree at three groups. The result is an integer membership vector; cluster labels are arbitrary and Stata generates a named dataset variable.
Stata reference · R reference
cluster kmeans x y z w, k(3)
stats::kmeans(scale(as.matrix(data[c("x","y","z","w")])),centers=3,nstart=10)
stats
Partition standardized observations into three k-means clusters
Differs from Stata: Algorithms, starts and random streams differ, so cluster numbering and local optima may differ.
Stata reference · R reference
cluster medianlinkage x y z w
stats::hclust(stats::dist(scale(as.matrix(data[c("x","y","z","w")]))),method="median")
stats
Fit medianlinkage hierarchical clustering on standardized variables
Differs from Stata: Standardize variables before the analogous Stata call. Ward distance and squaring conventions require care.
Stata reference · R reference
cluster singlelinkage x y z w
stats::hclust(stats::dist(scale(as.matrix(data[c("x","y","z","w")]))),method="single")
stats
Fit singlelinkage hierarchical clustering on standardized variables
Differs from Stata: Standardize variables before the analogous Stata call. Ward distance and squaring conventions require care.
Stata reference · R reference
cluster wardslinkage x y z w
stats::hclust(stats::dist(scale(as.matrix(data[c("x","y","z","w")]))),method="ward.D2")
stats
Fit wardslinkage hierarchical clustering on standardized variables
Differs from Stata: Standardize variables before the analogous Stata call. Ward distance and squaring conventions require care.
Stata reference · R reference
cluster waveragelinkage x y z w
stats::hclust(stats::dist(scale(as.matrix(data[c("x","y","z","w")]))),method="mcquitty")
stats
Fit waveragelinkage hierarchical clustering on standardized variables
Differs from Stata: Standardize variables before the analogous Stata call. Ward distance and squaring conventions require care.
Stata reference · R reference
clustermat completelinkage D
stats::hclust(stats::as.dist(D),method="complete")
stats
Cluster a precomputed dissimilarity matrix
Differs from Stata: Uses complete linkage on the supplied dissimilarity matrix. Dissimilarity definitions and tie breaking affect the tree; R returns an hclust object rather than a Stata named cluster solution.
Stata reference · R reference
discrim knn x y z w, group(g) k(5)
class::knn(train=as.matrix(data[c("x","y","z","w")]),test=as.matrix(data[c("x","y","z","w")]),cl=data$g,k=5)
class
Classify observations using five nearest neighbors
Differs from Stata: Selects predictors by name and classifies the training observations. class::knn uses unweighted majority voting and random tie breaking; Stata defaults to equal class priors, which can change decisions for unbalanced classes. Use held-out data for predictive accuracy.
Stata reference · R reference
discrim lda x y z w, group(g)
MASS::lda(g ~ x+y+z+w,data=data,prior=rep(1/3,3))
MASS
Fit LDA discriminant analysis
Differs from Stata: Prior class probabilities and covariance estimation conventions should be specified before comparing results.
Stata reference · R reference
discrim lda x y z w, group(g) lootable
MASS::lda(g ~ x+y+z+w,data=data,CV=TRUE,prior=rep(1/3,3))
MASS
Classify using leave-one-out linear discriminant analysis
Stata lootable requests leave-one-out classification; MASS CV=TRUE performs the corresponding prediction workflow.
Stata reference · R reference
discrim lda x y z w, group(g) priors(equal)
MASS::lda(g ~ x+y+z+w,data=data,prior=rep(1/3,3))
MASS
Use equal prior class probabilities in LDA
Differs from Stata: Equal class priors are explicit where shown. MASS coefficient normalization and class order can differ from Stata; compare posterior classifications after aligning priors and covariance estimates.
Stata reference · R reference
discrim qda x y z w, group(g)
{ analysis <- droplevels(stats::model.frame(g ~ x + y + z + w, data = data, na.action = stats::na.omit)); groups <- length(unique(analysis$g)); MASS::qda(g ~ x + y + z + w, data = analysis, prior = rep(1 / groups, groups)) }
MASS
Fit QDA discriminant analysis
Differs from Stata: Explicit equal priors are computed from classes remaining after complete-case filtering of the response and predictors, matching Stata discrim qda default priors(equal). MASS otherwise uses sample class proportions. Align covariance normalization and class labels before comparing posterior probabilities.
Stata reference · R reference
estat gof, stats(all)
lavaan::fitMeasures(fit,c("chisq","df","cfi","tli","rmsea","srmr"))
lavaan
Report confirmatory-factor model fit indices
Differs from Stata: Selects six lavaan SEM fit indices. Model identification, likelihood scaling, missing-data estimation and baseline-model definitions must match; this is not every statistic in Stata stats(all).
Stata reference · R reference
estat kmo
psych::KMO(stats::cor(X))
psych
Assess factorability using Kaiser-Meyer-Olkin measures
Differs from Stata: Computes KMO measures from the supplied correlation matrix. R returns overall and per-variable measures in a list; match the same correlation and missing-data sample used for Stata factor.
Stata reference · R reference
estat mindices
lavaan::modindices(fit)
lavaan
Inspect SEM modification indices
Differs from Stata: Returns lavaan modification indices for admissible freed parameters. Align model constraints, information matrix and missing-data likelihood; candidate parameter sets can differ from Stata.
Stata reference · R reference
estat residuals
lavaan::lavResiduals(fit,type="raw")
lavaan
Inspect residual correlations after SEM
Differs from Stata: Uses raw observed-minus-implied covariance residuals, matching Stata default raw residuals. lavaan also returns standardized summaries with its own scaling, which are not the same Stata output columns.
Stata reference · R reference
estat smc
1-1/diag(solve(stats::cor(X)))
stats
Compute squared multiple correlations for scale items
Differs from Stata: Computes squared multiple correlations as one minus the reciprocal diagonal of the inverse correlation matrix. Requires a nonsingular correlation matrix and returns a vector rather than Stata display tables.
Stata reference · R reference
factor q1 q2 q3 q4 q5 q6, factors(1) ml
stats::factanal(as.matrix(data[c("q1","q2","q3","q4","q5","q6")]),factors=1,rotation="none")
stats
Fit a one-factor maximum-likelihood factor model
Differs from Stata: Matches the stated ML or principal-component extraction and factor count. Loading signs and rotations are indeterminate; psych principal-component scores and scaling need not reproduce Stata factor postestimation.
Stata reference · R reference
factor q1 q2 q3 q4 q5 q6, factors(2) ipf
psych::fa(as.matrix(data[c("q1","q2","q3","q4","q5","q6")]),nfactors=2,fm="pa",rotate="none")
psych
Fit iterated principal-axis factors
Differs from Stata: Principal-axis algorithms and convergence tolerances vary; do not assume identical loadings.
Stata reference · R reference
factor q1 q2 q3 q4 q5 q6, factors(2) ml
stats::factanal(as.matrix(data[c("q1","q2","q3","q4","q5","q6")]),factors=2,rotation="none")
stats
Fit a two-factor maximum-likelihood factor model
Differs from Stata: Matches the stated ML or principal-component extraction and factor count. Loading signs and rotations are indeterminate; psych principal-component scores and scaling need not reproduce Stata factor postestimation.
Stata reference · R reference
factor q1 q2 q3 q4 q5 q6, factors(2) pcf
psych::principal(as.matrix(data[c("q1","q2","q3","q4","q5","q6")]),nfactors=2,rotate="none")
psych
Fit a principal-component factor solution
Differs from Stata: Matches the stated ML or principal-component extraction and factor count. Loading signs and rotations are indeterminate; psych principal-component scores and scaling need not reproduce Stata factor postestimation.
Stata reference · R reference
correlate q1 q2 q3 q4 q5 q6
matrix R = r(C)
factormat R, n(300) factors(2) ml
stats::factanal(covmat=R,n.obs=300,factors=2,rotation="none")
stats
Fit maximum-likelihood factors from a correlation matrix
Differs from Stata: Fixed workflow. R is a fixed correlation-matrix object; sample size supplies likelihood-based fit statistics.
Stata reference · R reference
hotelling x y
{ n <- nrow(data); k <- 2; m <- colMeans(data[c("x","y")]); T2 <- n*drop(t(m)%*%solve(stats::cov(data[c("x","y")]),m)); F <- (n-k)/(k*(n-1))*T2; c(T2=T2,F=F,p.value=stats::pf(F,k,n-k,lower.tail=FALSE)) }
stats
Test a vector of means against zero with Hotelling T squared
Differs from Stata: Computes the one-sample Hotelling T-squared and its F transformation for these two variables. Assumes a complete sample and invertible covariance; Stata additionally displays mean summaries.
Stata reference · R reference
kap rater1 rater2
psych::cohen.kappa(table(data$rater1,data$rater2))$kappa
psych
Estimate unweighted Cohen kappa for two raters
Differs from Stata: Returns unweighted Cohen kappa from the cross-tabulation. It omits Stata agreement summaries, standard errors and confidence intervals; align missing-value and category handling.
Stata reference · R reference
manova y z = g
summary(stats::manova(cbind(y,z)~g,data=data),test="Pillai")
stats
Test multivariate group differences using Pillai
Differs from Stata: Stata displays all four MANOVA statistics; this R example selects the named statistic.
Stata reference · R reference
manova y z = g c.x
stats::manova(cbind(y,z)~g+x,data=data)
stats
Fit multivariate analysis of covariance
Differs from Stata: Fits the stated multivariate linear model. R summary defaults to Pillai while Stata displays several multivariate criteria; choose the same criterion, hypothesis and factor contrasts.
Stata reference · R reference
manova y z = g
summary(stats::manova(cbind(y,z)~g,data=data),test="Wilks")
stats
Test multivariate group differences using Wilks
Differs from Stata: Stata displays all four MANOVA statistics; this R example selects the named statistic.
Stata reference · R reference
manova y z = g
summary(stats::manova(cbind(y,z)~g,data=data),test="Hotelling-Lawley")
stats
Test multivariate group differences using Hotelling-Lawley
Differs from Stata: Stata displays all four MANOVA statistics; this R example selects the named statistic.
Stata reference · R reference
manova y z = g
summary(stats::manova(cbind(y,z)~g,data=data),test="Roy")
stats
Test multivariate group differences using Roy
Differs from Stata: Stata displays all four MANOVA statistics; this R example selects the named statistic.
Stata reference · R reference
mca g h j, method(indicator)
MASS::mca(data, nf=2)
MASS
Analyze multiple categorical variables through indicator MCA
Differs from Stata: MASS uses an indicator-matrix MCA; inertia normalization differs from adjusted and joint MCA.
Stata reference · R reference
mds x y z w, id(id) dimension(2) noplot
stats::cmdscale(stats::dist(as.matrix(data[c("x","y","z","w")])),k=2,eig=TRUE)
stats
Fit classical metric multidimensional scaling
Differs from Stata: Uses classical metric scaling of Euclidean distances. Stata mds defaults and stress criteria can differ; coordinates are comparable only after aligning distances, method, rotation and reflection.
Stata reference · R reference
mds x y z w, id(id) method(nonmetric) std noplot
MASS::isoMDS(stats::dist(scale(as.matrix(data[c("x","y","z","w")]))),k=2,trace=FALSE)
MASS
Fit nonmetric multidimensional scaling
Differs from Stata: Nonmetric optimization, stress definitions and starting configurations can differ.
Stata reference · R reference
mdsmat D, dimension(2) noplot
stats::cmdscale(stats::as.dist(D),k=2)
stats
Scale an existing dissimilarity matrix
Differs from Stata: Applies classical metric scaling to the supplied dissimilarity matrix. Match Stata metric method and eigenvalue treatment; coordinate rotations and reflections are arbitrary.
Stata reference · R reference
mvreg y z = x w
stats::lm(cbind(y,z) ~ x+w,data=data)
stats
Fit multivariate multiple regression
Differs from Stata: Returns a multivariate lm fit on the common complete-case sample. Stata mvreg displays separate equations and cross-equation summaries; request the corresponding R summaries explicitly.
Stata reference · R reference
mvtest normality x y z w, stats(skewness kurtosis)
psych::mardia(X,plot=FALSE)
psych
Compute Mardia multivariate skewness and kurtosis tests
Differs from Stata: Finite-sample corrections may differ; this selects Mardia components rather than Stata default Doornik-Hansen.
Stata reference · R reference
pca x y z w
stats::prcomp(as.matrix(data[c("x","y","z","w")]),center=TRUE,scale.=TRUE)
stats
Fit correlation-matrix PCA
Differs from Stata: Selects correlation or covariance PCA explicitly. Component signs are arbitrary; prcomp returns singular-value-based objects and scores whose scaling differs from Stata displays.
Stata reference · R reference
pca x y z w, components(2)
stats::prcomp(as.matrix(data[c("x","y","z","w")]),scale.=TRUE,rank.=2)
stats
Retain two principal components
Differs from Stata: Selects correlation or covariance PCA explicitly. Component signs are arbitrary; prcomp returns singular-value-based objects and scores whose scaling differs from Stata displays.
Stata reference · R reference
pca x y z w, covariance
stats::prcomp(as.matrix(data[c("x","y","z","w")]),center=TRUE,scale.=FALSE)
stats
Fit covariance-matrix PCA
Differs from Stata: Selects correlation or covariance PCA explicitly. Component signs are arbitrary; prcomp returns singular-value-based objects and scores whose scaling differs from Stata displays.
Stata reference · R reference
correlate x y z w
matrix R = r(C)
pcamat R, n(50)
stats::princomp(covmat=R)
stats
Perform PCA directly on a correlation matrix
Differs from Stata: Fixed workflow.
Stata reference · R reference
predict p1 p2 p3, pr
data[c("p1","p2","p3")] <- stats::predict(fit)$posterior
MASS
Predict posterior probabilities for all discriminant classes
Differs from Stata: Uses the existing discriminant fit and its class order. Returned labels or posterior-probability columns must match the fitted classes; R factor order need not match Stata category codes.
Stata reference · R reference
predict pc1 pc2, score
data[c("pc1","pc2")] <- stats::predict(fit)[,1:2,drop=FALSE]
stats
Compute the first two principal-component scores
Differs from Stata: Returns scores from the existing PCA fit. R score scaling and arbitrary component signs can differ from Stata predict, score; align normalization before comparing values.
Stata reference · R reference
predict predicted, classification
data$predicted <- stats::predict(fit)$class
MASS
Predict discriminant-analysis class membership
Differs from Stata: Uses the existing discriminant fit and its class order. Returned labels or posterior-probability columns must match the fitted classes; R factor order need not match Stata category codes.
Stata reference · R reference
predict score1 score2, bartlett
data[c("score1","score2")] <- stats::factanal(as.matrix(data[c("q1","q2","q3","q4","q5","q6")]),factors=2,rotation="none",scores="Bartlett")$scores
stats
Compute Bartlett-method factor scores
Differs from Stata: Fixed measurement model with indicators q1-q6; output score names can be changed.
Stata reference · R reference
predict score1 score2, regression
data[c("score1","score2")] <- stats::factanal(as.matrix(data[c("q1","q2","q3","q4","q5","q6")]),factors=2,rotation="none",scores="regression")$scores
stats
Compute regression-method factor scores
Differs from Stata: Fixed measurement model with indicators q1-q6; output score names can be changed.
Stata reference · R reference
rotate, oblique oblimin
GPArotation::oblimin(unclass(fit$loadings))
GPArotation
Use the oblique oblimin loading-rotation criterion
Differs from Stata: Rotates the supplied loading matrix only. Loading signs, axis order and normalization can differ from Stata; correlated-factor solutions also require comparing the factor-correlation matrix.
Stata reference · R reference
rotate, orthogonal quartimax
GPArotation::quartimax(unclass(fit$loadings))
GPArotation
Use the orthogonal quartimax loading-rotation criterion
Differs from Stata: Rotates the supplied loading matrix only. Loading signs, axis order and normalization can differ from Stata; correlated-factor solutions also require comparing the factor-correlation matrix.
Stata reference · R reference
rotate, promax
stats::promax(fit$loadings,m=3)
stats
Rotate factor loadings using promax
Differs from Stata: Loadings are identified only up to sign and ordering; rotation normalization conventions may differ.
Stata reference · R reference
rotate, varimax
stats::varimax(fit$loadings,normalize=FALSE)
stats
Rotate factor loadings using varimax
Differs from Stata: Loadings are identified only up to sign and ordering; rotation normalization conventions may differ.
Stata reference · R reference
rotatemat L, varimax
stats::varimax(L)
stats
Rotate an externally supplied loading matrix
Differs from Stata: Applies varimax to the supplied matrix. Match normalization and column ordering; equivalent rotated solutions may reverse column signs.
Stata reference · R reference
sem (visual -> x1 x2 x3) (textual -> x4 x5 x6) (speed -> x7 x8 x9), latent(visual textual speed)
lavaan::cfa("visual =~ x1+x2+x3; textual =~ x4+x5+x6; speed =~ x7+x8+x9",data=data)
lavaan
Fit a three-factor confirmatory measurement model
Differs from Stata: Latent-variable scale constraints and mean structures must be aligned when comparing estimates.
Stata reference · R reference
sem, standardized
lavaan::standardizedSolution(fit)
lavaan
Report standardized SEM parameters
Differs from Stata: Fixed workflow.
Stata reference · R reference
tetrachoric a b
polycor::polychor(data$a,data$b,ML=TRUE,std.err=TRUE)
polycor
Estimate a tetrachoric correlation by maximum likelihood
Differs from Stata: Each binary variable must have two observed levels; inference assumes latent bivariate normality.
Stata reference · R reference

Power and precision planning

Stata R Purpose, qualifications and sources
ciwidth onemean, sd(2) n(50)
2*stats::qt(0.975,df=49)*2/sqrt(50)
stats
Calculate the anticipated full width of a mean interval
Anticipated-width workflow substituting the design SD for the future sample SD; interval width is upper minus lower. Stata also supports probability-of-width planning, which is not implemented here.
Stata reference · R reference
ciwidth onemean, sd(2) width(1)
ceiling(stats::uniroot(function(n) 2*stats::qt(0.975,n-1)*2/sqrt(n)-1,c(3,1000))$root)
stats
Plan n for a target mean-interval width
Anticipated-width workflow substituting the design SD for the future sample SD; interval width is upper minus lower. Stata also supports probability-of-width planning, which is not implemented here.
Stata reference · R reference
ciwidth pairedmeans, sddiff(2) n(50)
2*stats::qt(0.975,49)*2/sqrt(50)
stats
Calculate a paired mean-difference interval width
Anticipated-width workflow substituting the design SD for the future sample SD; interval width is upper minus lower. Stata also supports probability-of-width planning, which is not implemented here.
Stata reference · R reference
ciwidth twomeans, sd(2) n1(40) n2(60)
2*stats::qt(0.975,98)*2*sqrt(1/40+1/60)
stats
Calculate an equal-variance difference-of-means interval width
Anticipated-width workflow substituting the design SD for the future sample SD; interval width is upper minus lower. Stata also supports probability-of-width planning, which is not implemented here.
Stata reference · R reference
power onecorrelation 0 0.3, n(100)
pwr::pwr.r.test(r=0.3,n=100,sig.level=0.05)
pwr
Calculate correlation-test power at fixed n
Differs from Stata: pwr uses its documented approximation and effect-size parameterization; numerical results need not equal Stata.
Stata reference · R reference
power onecorrelation 0 0.3, power(0.8)
pwr::pwr.r.test(r=0.3,power=0.8,sig.level=0.05)
pwr
Plan sample size for detecting a correlation
Differs from Stata: pwr uses its documented approximation and effect-size parameterization; numerical results need not equal Stata.
Stata reference · R reference
power onecorrelation 0, n(100) power(0.8)
pwr::pwr.r.test(r=NULL,n=100,power=0.8,sig.level=0.05)
pwr
Find a detectable correlation at fixed n
Differs from Stata: pwr uses its documented approximation and effect-size parameterization; numerical results need not equal Stata.
Stata reference · R reference
power onemean 0 0.5, sd(1) knownsd n(40)
pwr::pwr.norm.test(d=0.5,n=40,sig.level=0.05)
pwr
Calculate one-mean z-test power with known SD
Differs from Stata: pwr reports the mean difference in SD units; knownsd distinguishes this from a t test.
Stata reference · R reference
power onemean 0 0.5, sd(1) knownsd power(0.8)
pwr::pwr.norm.test(d=0.5,power=0.8,sig.level=0.05)
pwr
Plan a one-mean z-test sample size with known SD
Differs from Stata: pwr reports the mean difference in SD units; knownsd distinguishes this from a t test.
Stata reference · R reference
power onemean 0 0.5, sd(1) n(40)
stats::power.t.test(n=40,delta=0.5,sd=1,type="one.sample",sig.level=0.05)
stats
Calculate power for a fixed-size onemean t test
Differs from Stata: Computes the displayed normal-theory t-test or two-proportion power design. R two-sample n is per group, whereas Stata n() is total; alternative, allocation and strict two-sided rejection conventions must match.
Stata reference · R reference
power onemean 0 0.5, sd(1) n(40) onesided
stats::power.t.test(n=40,delta=0.5,sd=1,type="one.sample",alternative="one.sided")
stats
Calculate one-sided one-mean t-test power
Differs from Stata: Computes the displayed normal-theory t-test or two-proportion power design. R two-sample n is per group, whereas Stata n() is total; alternative, allocation and strict two-sided rejection conventions must match.
Stata reference · R reference
power onemean 0 0.5, sd(1) power(0.8)
stats::power.t.test(delta=0.5,sd=1,type="one.sample",sig.level=0.05,power=0.8)
stats
Plan the sample size for a onemean t test
Differs from Stata: R reports n per group for an independent two-sample test; round sample sizes upward.
Stata reference · R reference
power onemean 0, sd(1) knownsd n(40) power(0.8)
pwr::pwr.norm.test(d=NULL,n=40,power=0.8,sig.level=0.05)
pwr
Find a detectable one-mean z-test effect
Differs from Stata: pwr reports the mean difference in SD units; knownsd distinguishes this from a t test.
Stata reference · R reference
power onemean 0, sd(1) n(40) power(0.8)
stats::power.t.test(n=40,delta=NULL,sd=1,power=0.8,type="one.sample")
stats
Find the detectable difference for a onemean t test
Differs from Stata: R returns a positive detectable difference; add it to the null mean to recover the alternative mean.
Stata reference · R reference
power oneproportion 0.3 0.5, n(100)
pwr::pwr.p.test(h=pwr::ES.h(0.5,0.3),n=100,sig.level=0.05)
pwr
Approximate one-proportion power for a fixed sample
Uses the arcsine effect h, an alternative to Stata default score-test calculations.
Stata reference · R reference
power oneproportion 0.3 0.5, power(0.8)
pwr::pwr.p.test(h=pwr::ES.h(0.5,0.3),power=0.8,sig.level=0.05)
pwr
Approximate a one-proportion design using Cohen h
Uses the arcsine effect h, an alternative to Stata default score-test calculations.
Stata reference · R reference
power oneway 0 0.5 1, varerror(1) n(90)
pwr::pwr.anova.test(k=3,n=30,f=sqrt(mean((c(0,0.5,1)-0.5)^2)))
pwr
Calculate balanced one-way ANOVA power
Differs from Stata: pwr uses its documented approximation and effect-size parameterization; numerical results need not equal Stata.
Stata reference · R reference
power oneway 0 0.5 1, varerror(1) power(0.8)
pwr::pwr.anova.test(k=3,f=sqrt(mean((c(0,0.5,1)-0.5)^2)),power=0.8)
pwr
Plan balanced one-way ANOVA group size
Differs from Stata: pwr uses its documented approximation and effect-size parameterization; numerical results need not equal Stata.
Stata reference · R reference
power pairedmeans 0 0.5, sddiff(1) n(40)
stats::power.t.test(n=40,delta=0.5,sd=1,type="paired",sig.level=0.05)
stats
Calculate power for a fixed-size pairedmeans t test
Differs from Stata: Computes the displayed normal-theory t-test or two-proportion power design. R two-sample n is per group, whereas Stata n() is total; alternative, allocation and strict two-sided rejection conventions must match.
Stata reference · R reference
power pairedmeans 0 0.5, sddiff(1) power(0.8)
stats::power.t.test(delta=0.5,sd=1,type="paired",sig.level=0.05,power=0.8)
stats
Plan the sample size for a pairedmeans t test
Differs from Stata: R reports n per group for an independent two-sample test; round sample sizes upward.
Stata reference · R reference
power pairedmeans 0, sddiff(1) n(40) power(0.8)
stats::power.t.test(n=40,delta=NULL,sd=1,power=0.8,type="paired")
stats
Find the detectable difference for a pairedmeans t test
Differs from Stata: R returns a positive detectable difference; add it to the null mean to recover the alternative mean.
Stata reference · R reference
power rsquared 0.1, n(100) ntested(3)
pwr::pwr.f2.test(u=3,v=96,f2=0.1/(1-0.1))
pwr
Calculate power for an overall three-predictor R squared test
Differs from Stata: f2=(R2_full-R2_reduced)/(1-R2_full); residual df is N minus all predictors minus one.
Stata reference · R reference
power rsquared 0.1, power(0.8) ntested(3)
{ design <- pwr::pwr.f2.test(u=3,f2=0.1/(1-0.1),power=0.8); ceiling(design$v+3+1) }
pwr
Plan total n for an overall R squared test
Differs from Stata: f2=(R2_full-R2_reduced)/(1-R2_full); residual df is N minus all predictors minus one.
Stata reference · R reference
power rsquared 0.2 0.3, n(120) ntested(2) ncontrol(3)
pwr::pwr.f2.test(u=2,v=114,f2=(0.3-0.2)/(1-0.3))
pwr
Calculate power for incremental explained variance
Differs from Stata: f2=(R2_full-R2_reduced)/(1-R2_full); residual df is N minus all predictors minus one.
Stata reference · R reference
power twomeans 0 0.5, sd(1) n(80)
stats::power.t.test(n=40.0,delta=0.5,sd=1,type="two.sample",sig.level=0.05)
stats
Calculate power for a fixed-size twomeans t test
Differs from Stata: Computes the displayed normal-theory t-test or two-proportion power design. R two-sample n is per group, whereas Stata n() is total; alternative, allocation and strict two-sided rejection conventions must match.
Stata reference · R reference
power twomeans 0 0.5, sd(1) n1(30) n2(50)
pwr::pwr.t2n.test(n1=30,n2=50,d=0.5,sig.level=0.05)
pwr
Calculate power with unequal independent group sizes
Differs from Stata: Uses the pooled-variance standardized mean-difference model; this is not a Welch heteroskedastic design.
Stata reference · R reference
power twomeans 0 0.5, sd(1) power(0.8)
stats::power.t.test(delta=0.5,sd=1,type="two.sample",sig.level=0.05,power=0.8)
stats
Plan the sample size for a twomeans t test
Differs from Stata: R reports n per group for an independent two-sample test; round sample sizes upward.
Stata reference · R reference
power twomeans 0, sd(1) n(80) power(0.8)
stats::power.t.test(n=40.0,delta=NULL,sd=1,power=0.8,type="two.sample")
stats
Find the detectable difference for a twomeans t test
Differs from Stata: R returns a positive detectable difference; add it to the null mean to recover the alternative mean.
Stata reference · R reference
power twoproportions 0.3 0.5, n(200)
stats::power.prop.test(n=100,p1=0.3,p2=0.5,sig.level=0.05)
stats
Calculate power for two fixed-size proportion samples
Differs from Stata: Computes the displayed normal-theory t-test or two-proportion power design. R two-sample n is per group, whereas Stata n() is total; alternative, allocation and strict two-sided rejection conventions must match.
Stata reference · R reference
power twoproportions 0.3 0.5, n(200) onesided
stats::power.prop.test(n=100,p1=0.3,p2=0.5,alternative="one.sided")
stats
Calculate one-sided two-proportion power
Differs from Stata: Computes the displayed normal-theory t-test or two-proportion power design. R two-sample n is per group, whereas Stata n() is total; alternative, allocation and strict two-sided rejection conventions must match.
Stata reference · R reference
power twoproportions 0.3 0.5, power(0.8)
stats::power.prop.test(p1=0.3,p2=0.5,power=0.8,sig.level=0.05)
stats
Plan sample size for two independent proportions
Differs from Stata: R reports sample size per group. Normal-approximation conventions and continuity corrections may differ.
Stata reference · R reference
power twoproportions 0.3, n(200) power(0.8)
stats::power.prop.test(n=100,p1=0.3,p2=NULL,power=0.8,sig.level=0.05)
stats
Find a detectable alternative proportion
Differs from Stata: Computes the displayed normal-theory t-test or two-proportion power design. R two-sample n is per group, whereas Stata n() is total; alternative, allocation and strict two-sided rejection conventions must match.
Stata reference · R reference

Resampling and simulation

Stata R Purpose, qualifications and sources
bayesboot _b[x], reps(199): regress y x
replicate(199,{ weights <- stats::rexp(nrow(data)); unname(stats::coef(stats::lm(y~x,data=data,weights=weights))["x"]) })
stats
Use Bayesian-bootstrap Dirichlet weights for a slope
Fixed workflow. Independent exponential weights normalized to sum one are Dirichlet(1,...,1); common scaling does not change weighted least-squares coefficients.
Stata reference · R reference
bootstrap _b, reps(199) strata(g): regress y x
boot::boot(data,statistic=function(d,i) stats::coef(stats::lm(y~x,data=d[i,])),R=199,strata=data$g)
boot
Bootstrap regression coefficients within fixed strata
Fixed workflow. Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
bootstrap difference=(_b[x]-_b[z]), reps(199): regress y x z
boot::boot(data,statistic=function(d,i) unname(diff(stats::coef(stats::lm(y~x+z,data=d[i,]))[c("z","x")])),R=199)
boot
Bootstrap a difference between regression slopes
Fixed workflow. Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
bootstrap mean=r(mean), reps(199) cluster(g): summarize y
{ ids <- unique(data$g); replicate(199,{ picked <- sample(ids,length(ids),replace=TRUE); sample_data <- do.call(rbind,lapply(picked,function(id) data[data$g==id,,drop=FALSE])); mean(sample_data$y) }) }
base
Bootstrap a mean by resampling complete clusters
Fixed workflow. Resamples cluster identifiers, retaining every observation in each selected cluster. Three clusters are only a demonstration.
Stata reference · R reference
bootstrap mean=r(mean), reps(199): summarize y
boot::boot(data,statistic=function(d,i) mean(d$y[i]),R=199)
boot
Bootstrap the sample mean
Fixed workflow. Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
bootstrap mean=r(mean), reps(499) bca: summarize y
{ boot_fit <- boot::boot(data,function(d,i) mean(d$y[i]),R=499); boot::boot.ci(boot_fit,type="bca") }
boot
Compute a bias-corrected accelerated bootstrap interval
Fixed workflow. Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
bootstrap median=r(p50), reps(199): summarize y, detail
boot::boot(data,statistic=function(d,i) stats::median(d$y[i]),R=199)
boot
Bootstrap the sample median
Fixed workflow. Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
bootstrap q1=r(p25), reps(199): summarize y, detail
boot::boot(data,statistic=function(d,i) unname(stats::quantile(d$y[i],0.25,type=2)),R=199)
boot
Bootstrap the lower quartile
Fixed workflow. Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
bootstrap q3=r(p75), reps(199): summarize y, detail
boot::boot(data,statistic=function(d,i) unname(stats::quantile(d$y[i],0.75,type=2)),R=199)
boot
Bootstrap the upper quartile
Fixed workflow. Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
bootstrap sd=r(sd), reps(199): summarize y
boot::boot(data,statistic=function(d,i) stats::sd(d$y[i]),R=199)
boot
Bootstrap the sample standard deviation
Fixed workflow. Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
bootstrap slope=_b[x], reps(199): regress y x
boot::boot(data,statistic=function(d,i) unname(stats::coef(stats::lm(y~x,data=d[i,]))["x"]),R=199)
boot
Bootstrap a regression slope by resampling rows
Fixed workflow. Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
bootstrap variance=r(Var), reps(199): summarize y
boot::boot(data,statistic=function(d,i) stats::var(d$y[i]),R=199)
boot
Bootstrap the sample variance
Fixed workflow. Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
bsample
data[sample.int(nrow(data),nrow(data),replace=TRUE),,drop=FALSE]
base
Draw a nonparametric row-bootstrap sample
Fixed workflow. Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
bsample, strata(g)
do.call(rbind,lapply(split(data,data$g),function(d) d[sample.int(nrow(d),nrow(d),replace=TRUE),,drop=FALSE]))
base
Draw a stratified row-bootstrap sample
Fixed workflow. Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
bstat
c(estimate=boot_fit$t0,bias=mean(boot_fit$t)-boot_fit$t0,se=stats::sd(boot_fit$t))
stats
Summarize stored bootstrap estimates, bias and standard error
Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
estat bootstrap, normal
boot::boot.ci(boot_fit,type="norm")
boot
Compute a normal bootstrap interval
Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
estat bootstrap, percentile
boot::boot.ci(boot_fit,type="perc")
boot
Compute a percentile bootstrap interval
Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
jackknife _b[x]: regress y x
{ n <- nrow(data); deleted <- vapply(seq_len(n),function(i) unname(stats::coef(stats::lm(y~x,data=data[-i,]))["x"]),numeric(1)); c(estimate=unname(stats::coef(stats::lm(y~x,data=data))["x"]),se=sqrt((n-1)/n*sum((deleted-mean(deleted))^2))) }
stats
Jackknife a regression slope
Fixed workflow. The delete-one jackknife is deterministic; its variance uses (n-1)/n times the squared deviations of the replicate estimates.
Stata reference · R reference
jackknife mean=r(mean), rclass cluster(g): summarize y
{ groups <- unique(data$g); deleted <- vapply(groups,function(id) mean(data$y[data$g!=id]),numeric(1)); length(groups) }
base
Enumerate delete-one-cluster jackknife replicates
Fixed workflow. Returns replicate count and retains deleted estimates. Unequal cluster-size variance corrections need an explicitly chosen jackknife design.
Stata reference · R reference
jackknife mean=r(mean), rclass keep: summarize y
{ n <- nrow(data); deleted <- vapply(seq_len(n),function(i) mean(data$y[-i]),numeric(1)); n*mean(data$y)-(n-1)*deleted }
base
Generate jackknife pseudovalues for the sample mean
Fixed workflow. The delete-one jackknife is deterministic; its variance uses (n-1)/n times the squared deviations of the replicate estimates.
Stata reference · R reference
jackknife mean=r(mean), rclass: summarize y
{ n <- nrow(data); deleted <- vapply(seq_len(n),function(i) mean(data$y[-i]),numeric(1)); c(estimate=mean(data$y),se=sqrt((n-1)/n*sum((deleted-mean(deleted))^2))) }
stats
Jackknife the sample mean
Fixed workflow. The delete-one jackknife is deterministic; its variance uses (n-1)/n times the squared deviations of the replicate estimates.
Stata reference · R reference
jackknife sd=r(sd), rclass: summarize y
{ n <- nrow(data); deleted <- vapply(seq_len(n),function(i) stats::sd(data$y[-i]),numeric(1)); c(estimate=stats::sd(data$y),se=sqrt((n-1)/n*sum((deleted-mean(deleted))^2))) }
stats
Jackknife the sample standard deviation
Fixed workflow. The delete-one jackknife is deterministic; its variance uses (n-1)/n times the squared deviations of the replicate estimates.
Stata reference · R reference
permute y _b[x], reps(199) strata(g): regress y x
replicate(199,{ d <- data; d$y <- unsplit(lapply(split(data$y,data$g),sample),data$g); unname(stats::coef(stats::lm(y~x,data=d))["x"]) })
stats
Permute outcomes within fixed strata
Fixed workflow. Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
permute y _b[x], reps(199): regress y x
replicate(199,{ d <- data; d$y <- sample(d$y); unname(stats::coef(stats::lm(y~x,data=d))["x"]) })
stats
Generate a permutation distribution for a regression slope
Fixed workflow. Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
permute y r(rho), reps(199): correlate y x
replicate(199,stats::cor(sample(data$y),data$x))
stats
Generate a permutation distribution for a correlation
Fixed workflow. Random streams and resampling defaults differ across software; a fixed R seed makes this workflow reproducible.
Stata reference · R reference
program define mymean, rclass
    preserve
    clear
    set obs 40
    generate y = rnormal(2,1)
    summarize y
    local estimate = r(mean)
    restore
    return scalar mean = `estimate'
end
simulate mean=r(mean), reps(199): mymean
replicate(199,mean(stats::rnorm(40,mean=2,sd=1)))
stats
Simulate the sampling distribution of a normal sample mean
Fixed workflow. mymean is a user-defined Stata program drawing 40 normal(2,1) observations and returning their mean; this is a fixed workflow.
Stata reference · R reference

Model reporting

Stata R Purpose, qualifications and sources
estimates stats
broom::glance(fit)
broom
Extract one-row model fit statistics
Workflow alternative returning an R table; it does not reproduce Stata table formatting.
Stata reference · R reference
etable, cstat(_r_b) cstat(_r_se)
broom::tidy(fit,conf.int=TRUE)
broom
Create a tidy coefficient table with uncertainty
Fixed workflow. Workflow alternative returning an R table; it does not reproduce Stata table formatting.
Stata reference · R reference
predict result, residuals
broom::augment(fit)
broom
Attach fitted values, residuals and influence diagnostics
Fixed workflow. Workflow alternative returning an R table; it does not reproduce Stata table formatting.
Stata reference · R reference

Spatial workflows

Stata R Purpose, qualifications and sources
spbalance, balance
{ counts <- table(data$time); common <- as.numeric(names(counts)[counts == length(unique(data$id))]); data[data$time %in% common, , drop = FALSE] }
base
Balance a spatial panel by retaining common time periods
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Requires unique unit/time pairs. Mirrors spbalance's choice to drop incomplete time periods while retaining spatial units; it does not fill missing outcomes.
Stata reference · R reference
spdistance 1 2
sqrt(sum((as.numeric(data[data$id == 1, c("x", "y")]) - as.numeric(data[data$id == 2, c("x", "y")]))^2))
base
Distance between two identified planar locations
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Planar Euclidean distance only; longitude/latitude require a geodesic calculation and explicit units.
Stata reference · R reference
spgenerate nearby = W*value
drop(W %*% data$value)
base
Compute a spatially lagged covariate
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. W must use the identical unit ordering as data; this operation does not fit a spatial autoregressive model.
Stata reference · R reference
spmatrix create idistance W, normalize(row)
{ D <- as.matrix(stats::dist(data[c("x", "y")])); W <- matrix(0, nrow(D), ncol(D)); off <- row(D) != col(D); W[off] <- 1 / D[off]; W / rowSums(W) }
stats
Row-standardized inverse-distance spatial weights
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Planar distances, distinct non-coincident locations and matching row/column ID order are required. Stata defaults to spectral normalization, so row normalization is explicit.
Stata reference · R reference
spset id, coord(x y)
sf::st_as_sf(data, coords = c("x", "y"), crs = 3857, remove = FALSE)
sf
Declare planar point geometry and coordinate reference system
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Creating an sf object does not set Stata dataset metadata. Coordinates and CRS must describe the actual data; do not assign a projected CRS to longitude/latitude.
Stata reference · R reference

Causal inference

Stata R Purpose, qualifications and sources
boottest treat, cluster(group) reps(199) weighttype(rademacher) seed(128)
fwildclusterboot::boottest(fit, param = "treat", clustid = "group", B = 199, type = "rademacher", impose_null = TRUE, conf_int = FALSE, engine = "R-lean")
fwildclusterboot
Null-imposed wild cluster bootstrap using rademacher weights
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Small replication count is a runnable example, not an analysis recommendation. Align bootstrap variant, clustering and finite-sample correction. Installed fwildclusterboot emits a one-time seeding-change warning; both R and dqrng generators are explicitly seeded. fwildclusterboot 0.13 changed RNG seeding; seed-for-seed agreement with older versions is not expected.
Stata reference · R reference
boottest treat, cluster(group) reps(199) weighttype(webb) seed(128)
fwildclusterboot::boottest(fit, param = "treat", clustid = "group", B = 199, type = "webb", impose_null = TRUE, conf_int = FALSE, engine = "R-lean")
fwildclusterboot
Null-imposed wild cluster bootstrap using webb weights
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Small replication count is a runnable example, not an analysis recommendation. Align bootstrap variant, clustering and finite-sample correction. Installed fwildclusterboot emits a one-time seeding-change warning; both R and dqrng generators are explicitly seeded. fwildclusterboot 0.13 changed RNG seeding; seed-for-seed agreement with older versions is not expected.
Stata reference · R reference
cem category, treatment(treat)
MatchIt::matchit(treat ~ category, data = transform(data, category = as.integer(category) - 1L), method = "cem", estimand = "ATT", cutpoints = list(category = 0))
MatchIt
Coarsened exact matching on a categorical covariate
Fixed workflow; adapt the named data columns explicitly. Matching preprocessing only; categorical levels need no continuous cutpoints. For continuous variables, explicitly match cutpoints and estimand rather than relying on different software defaults.
Stata reference · R reference
did_imputation y id time cohort
{ baseline <- stats::lm(y ~ factor(id) + factor(time) + x, data = data, subset = treated == 0); effects <- data$y - stats::predict(baseline, newdata = data); mean(effects[data$treated == 1]) }
stats
Average imputation treatment effect over treated observations
Fixed workflow; adapt the named data columns explicitly. Point-estimation workflow only; untreated-outcome model, weighting and supported treated observations must be chosen explicitly.
Stata reference · R reference
did_imputation y id time cohort, allhorizons
{ untreated <- data$treated == 0; baseline <- stats::lm(y ~ factor(id) + factor(time) + x, data = data, subset = untreated); effects <- data$y - stats::predict(baseline, newdata = data); keep <- data$treated == 1; stats::aggregate(effects[keep], list(horizon = data$time[keep] - data$cohort[keep]), mean) }
stats
Untreated-outcome imputation effects by event time
Fixed workflow; adapt the named data columns explicitly. Point-estimation illustration with unit/time effects learned only from untreated observations. Never-treated Stata cohort should be missing, whereas this R fixture uses an out-of-range sentinel. Does not reproduce did_imputation's influence-function variance, autosample or pretrend tests.
Stata reference · R reference
drdid y x, ivar(id) time(time) treatment(treated) dripw
{ ps <- stats::fitted(stats::glm(treated ~ x, data = data, family = stats::binomial())); m0 <- stats::predict(stats::lm(dy ~ x, data = data, subset = treated == 0), data); weighted.mean(data$dy - m0, data$treated) - weighted.mean(data$dy - m0, (1 - data$treated) * ps / (1 - ps)) }
stats
Two-period panel doubly robust DiD ATT point estimate
Fixed workflow; adapt the named data columns explicitly. Wide-data point-estimation workflow for the dripw variant: logistic propensity plus control-group outcome-change OLS. Stata expects long data. No influence-function variance or improved drimp estimator.
Stata reference · R reference
drdid y x, ivar(id) time(time) treatment(treated) reg
{ m0 <- stats::predict(stats::lm(dy ~ x, data = data, subset = treated == 0), data); mean((data$dy - m0)[data$treated == 1]) }
stats
Panel outcome-regression DiD ATT point estimate
Fixed workflow; adapt the named data columns explicitly. Two-period wide-data regression-adjustment workflow; requires conditional parallel trends and no anticipation. No standard errors.
Stata reference · R reference
drdid y x, ivar(id) time(time) treatment(treated) stdipw
{ ps <- stats::fitted(stats::glm(treated ~ x, data = data, family = stats::binomial())); mean(data$dy[data$treated == 1]) - weighted.mean(data$dy, (1 - data$treated) * ps / (1 - ps)) }
stats
Stabilized inverse-probability-weighted DiD ATT
Fixed workflow; adapt the named data columns explicitly. Two-period wide-data point estimate; no influence-function variance and no repeated-cross-section implementation.
Stata reference · R reference
ebalance treat x z, targets(1)
WeightIt::weightit(treat ~ x + z, data = data, method = "ebal", estimand = "ATT", moments = 1)
WeightIt
Entropy balancing treated/control covariate moments through order 1
Fixed workflow; adapt the named data columns explicitly. Preprocessing weights targeting the treated population; normalization, higher moments and optimization tolerances must match. No outcome standard errors.
Stata reference · R reference
ebalance treat x z, targets(2)
WeightIt::weightit(treat ~ x + z, data = data, method = "ebal", estimand = "ATT", moments = 2)
WeightIt
Entropy balancing treated/control covariate moments through order 2
Fixed workflow; adapt the named data columns explicitly. Preprocessing weights targeting the treated population; normalization, higher moments and optimization tolerances must match. No outcome standard errors.
Stata reference · R reference
estat endogenous
summary(AER::ivreg(y ~ x + w | z + w, data = data), diagnostics = TRUE)$diagnostics
AER
IV weak-instrument and endogeneity diagnostics
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Wu-Hausman tests depend on model assumptions; exactly identified models have no overidentification test.
Stata reference · R reference
estat firststage
summary(stats::lm(x ~ z + w, data = data))
stats
First-stage instrument relevance regression
Fixed workflow; adapt the named data columns explicitly. This is the full first-stage regression; a joint excluded-instrument F test may require a nested comparison.
Stata reference · R reference
eventstudyinteract y lead3 lead2 lag0 lag1 lag2, absorb(id time) cohort(cohort) control_cohort(never)
{ fit <- fixest::feols(y ~ sunab(cohort, time, ref.p = -1) | id + time, data = data, vcov = ~id, nthreads = 1); stats::aggregate(fit, agg = "ATT") }
fixest
Aggregate cohort-interacted post-treatment effects
Fixed workflow; adapt the named data columns explicitly. ATT aggregation is an R postestimation step; match event-time/cohort weights rather than averaging coefficients unweighted.
Stata reference · R reference
eventstudyinteract y lead3 lead2 lag0 lag1 lag2, absorb(id time) cohort(cohort) control_cohort(never) covariates(x) vce(cluster id)
fixest::feols(y ~ sunab(cohort, time, ref.p = -1) + x | id + time, data = data, vcov = ~id, nthreads = 1)
fixest
Sun-Abraham cohort-interacted event-study estimation
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Uses never-treated reference cohorts and -1 event-time reference. Match supported horizons, cohort-share aggregation and covariance conventions to eventstudyinteract.
Stata reference · R reference
gencohort cohort, group(id) time(time) treat(treated)
transform(data, cohort = ave(ifelse(treated == 1, time, Inf), id, FUN = function(v) { first <- min(v); rep(if(is.infinite(first)) 0 else first, length(v)) }))
stats
Create first-treatment cohorts including never-treated units
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Uses zero as a never-treated category for cohort-based DiD. An absorbing treatment history and unique unit/time records are prerequisites; imputation estimators may instead require missing never-treatment times.
Stata reference · R reference
ivreghdfe y z (x = instrument), absorb(id time)
fixest::feols(y ~ z | id + time | x ~ instrument, data = data, vcov = "iid", nthreads = 1)
fixest
Instrumental variables with two absorbed effects
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. User-written Stata command. Match singleton handling, covariance correction and absorbed-effect degrees of freedom before comparing inferential output.
Stata reference · R reference
ivreghdfe y z (x = instrument), absorb(id time) cluster(id)
fixest::feols(y ~ z | id + time | x ~ instrument, data = data, vcov = ~id, nthreads = 1)
fixest
Cluster-robust absorbed-effects IV
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. User-written Stata command. Match singleton handling, covariance correction and absorbed-effect degrees of freedom before comparing inferential output.
Stata reference · R reference
ivreghdfe y z (x = instrument), absorb(id time) robust
fixest::feols(y ~ z | id + time | x ~ instrument, data = data, vcov = "hetero", nthreads = 1)
fixest
Heteroskedasticity-robust absorbed-effects IV
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. User-written Stata command. Match singleton handling, covariance correction and absorbed-effect degrees of freedom before comparing inferential output.
Stata reference · R reference
ivreghdfe y z (x = instrument), absorb(id)
fixest::feols(y ~ z | id | x ~ instrument, data = data, vcov = "iid", nthreads = 1)
fixest
Instrumental variables with individual fixed effects
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. User-written Stata command. Match singleton handling, covariance correction and absorbed-effect degrees of freedom before comparing inferential output.
Stata reference · R reference
ivregress 2sls y w (x = z)
AER::ivreg(y ~ x + w | z + w, data = data)
AER
Formula-based instrumental-variable regression
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Separate structural regressors and instruments with the formula bar.
Stata reference · R reference
ivregress 2sls y w (x = z), vce(cluster cluster)
estimatr::iv_robust(y ~ x + w | z + w, data = data, clusters = cluster, se_type = "stata")
estimatr
Cluster-robust two-stage least squares
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Small-cluster reference degrees of freedom are explicit.
Stata reference · R reference
ivregress 2sls y w (x = z), vce(robust)
estimatr::iv_robust(y ~ x + w | z + w, data = data, se_type = "HC2")
estimatr
Two-stage least squares with HC2 covariance
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. HC corrections differ; estimatr stata aliases HC1 for unclustered IV inference.
Stata reference · R reference
ivregress 2sls y w (x = z), vce(robust)
estimatr::iv_robust(y ~ x + w | z + w, data = data, se_type = "HC3")
estimatr
Two-stage least squares with HC3 covariance
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. HC corrections differ; estimatr stata aliases HC1 for unclustered IV inference.
Stata reference · R reference
ivregress 2sls y w (x = z), vce(robust) small
estimatr::iv_robust(y ~ x + w | z + w, data = data, se_type = "HC1")
estimatr
Two-stage least squares with HC1 covariance
Differs from Stata: Stata small requests the N/(N-K) HC1 correction and t-based inference. estimatr se_type="stata" aliases HC1 for unclustered IV. Without small, ivregress vce(robust) uses HC0 and normal reference inference, so it is a different default.
Stata reference · R reference
ivregress 2sls y w (x = z), vce(robust) small
estimatr::iv_robust(y ~ x + w | z + w, data = data, se_type = "stata")
estimatr
Two-stage least squares with stata covariance
Differs from Stata: Stata small requests the N/(N-K) HC1 correction and t-based inference. estimatr se_type="stata" aliases HC1 for unclustered IV. Without small, ivregress vce(robust) uses HC0 and normal reference inference, so it is a different default.
Stata reference · R reference
kmatch eb treat x z (y), att targets(1)
WeightIt::weightit(treat ~ x + z, data = data, method = "ebal", estimand = "ATT", moments = 1)
WeightIt
Entropy balancing treated/control covariate moments through order 1
Fixed workflow; adapt the named data columns explicitly. Preprocessing weights targeting the treated population; normalization, higher moments and optimization tolerances must match. No outcome standard errors.
Stata reference · R reference
kmatch eb treat x z (y), att targets(2)
WeightIt::weightit(treat ~ x + z, data = data, method = "ebal", estimand = "ATT", moments = 2)
WeightIt
Entropy balancing treated/control covariate moments through order 2
Fixed workflow; adapt the named data columns explicitly. Preprocessing weights targeting the treated population; normalization, higher moments and optimization tolerances must match. No outcome standard errors.
Stata reference · R reference
kmatch em treat category (y), att
MatchIt::matchit(treat ~ category, data = data, method = "exact", estimand = "ATT")
MatchIt
Exact matching on categorical covariates
Fixed workflow; adapt the named data columns explicitly. Exact-match preprocessing; estimand and stratum normalization are explicit.
Stata reference · R reference
kmatch ipw treat x z (y), att
WeightIt::weightit(treat ~ x + z, data = data, method = "glm", estimand = "ATT")
WeightIt
Inverse-probability weighting for the treated population
Fixed workflow; adapt the named data columns explicitly. Weights only; outcome contrasts and propensity-estimation variance require a separate estimator.
Stata reference · R reference
kmatch md treat x z (y), att nn(1)
MatchIt::matchit(treat ~ x + z, data = data, method = "nearest", distance = "mahalanobis", replace = TRUE, estimand = "ATT")
MatchIt
Multivariate Mahalanobis matching
Fixed workflow; adapt the named data columns explicitly. Explicit nearest-neighbor alternative to kmatch's kernel defaults; matching preprocessing only.
Stata reference · R reference
kmatch ps treat x z (y), att nn(1)
MatchIt::matchit(treat ~ x + z, data = data, method = "nearest", distance = "glm", replace = TRUE, estimand = "ATT")
MatchIt
Propensity-score nearest-neighbor matching
Fixed workflow; adapt the named data columns explicitly. Explicit nearest-neighbor alternative to kmatch's kernel defaults; matching preprocessing only.
Stata reference · R reference
psmatch2 treat x z, outcome(y) logit neighbor(1)
MatchIt::matchit(treat ~ x + z, data = data, method = "nearest", distance = "glm", link = "logit", replace = TRUE, estimand = "ATT")
MatchIt
Propensity-score nearest matching with replacement
Fixed workflow; adapt the named data columns explicitly. Returns matching preprocessing, not psmatch2's outcome estimate or variance. Replacement, tie-breaking and match order must be explicit.
Stata reference · R reference
psmatch2 treat x z, outcome(y) logit neighbor(1)
{ match <- MatchIt::matchit(treat ~ x + z, data = data, method = "nearest", distance = "glm", replace = TRUE, estimand = "ATT"); matched <- MatchIt::match_data(match); with(matched, weighted.mean(y[treat == 1], weights[treat == 1]) - weighted.mean(y[treat == 0], weights[treat == 0])) }
MatchIt
Matched ATT point contrast after propensity-score preprocessing
Fixed workflow; adapt the named data columns explicitly. Point contrast only; variance is not estimated, and matching ties/order may differ.
Stata reference · R reference
psmatch2 treat x z, outcome(y) logit neighbor(1) caliper(.1)
MatchIt::matchit(treat ~ x + z, data = data, method = "nearest", distance = "glm", link = "logit", replace = TRUE, caliper = .1, std.caliper = FALSE, estimand = "ATT")
MatchIt
Propensity-score matching with an absolute caliper
Fixed workflow; adapt the named data columns explicitly. Absolute probability-scale caliper; MatchIt defaults to standardized calipers unless explicitly disabled. Outcome estimation remains separate.
Stata reference · R reference
psmatch2 treat x z, outcome(y) logit neighbor(1) noreplacement
MatchIt::matchit(treat ~ x + z, data = data, method = "nearest", distance = "glm", link = "logit", replace = FALSE, estimand = "ATT")
MatchIt
Propensity-score nearest matching without replacement
Fixed workflow; adapt the named data columns explicitly. Returns matching preprocessing, not psmatch2's outcome estimate or variance. Replacement, tie-breaking and match order must be explicit.
Stata reference · R reference
psmatch2 treat, outcome(y) mahalanobis(x z) neighbor(1)
MatchIt::matchit(treat ~ x + z, data = data, method = "nearest", distance = "mahalanobis", replace = TRUE, estimand = "ATT")
MatchIt
Mahalanobis matching with replacement
Fixed workflow; adapt the named data columns explicitly. Matching preprocessing; covariance normalization and ties may differ from psmatch2.
Stata reference · R reference
pstest x z, both
cobalt::bal.tab(match, un = TRUE)
cobalt
Standardized covariate balance before and after matching
Fixed workflow; adapt the named data columns explicitly. Companion command supplied with psmatch2. Choose the same standardization denominator; cobalt's balance table does not reproduce every pstest t-test or omnibus summary.
Stata reference · R reference
rdbwdensity x
rddensity::rdbwdensity(x)
rddensity
Bandwidth selection for density discontinuity
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Bandwidths optimize density-estimation criteria, not treatment-effect estimation.
Stata reference · R reference
rdbwselect y x, bwselect(cerrd)
rdrobust::rdbwselect(y, x, bwselect = "cerrd")
rdrobust
RD bandwidth selection: cerrd
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Official rdrobust companion command; bandwidth selectors target different criteria.
Stata reference · R reference
rdbwselect y x, bwselect(certwo)
rdrobust::rdbwselect(y, x, bwselect = "certwo")
rdrobust
RD bandwidth selection: certwo
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Official rdrobust companion command; bandwidth selectors target different criteria.
Stata reference · R reference
rdbwselect y x, bwselect(mserd)
rdrobust::rdbwselect(y, x, bwselect = "mserd")
rdrobust
RD bandwidth selection: mserd
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Official rdrobust companion command; bandwidth selectors target different criteria.
Stata reference · R reference
rdbwselect y x, bwselect(msetwo)
rdrobust::rdbwselect(y, x, bwselect = "msetwo")
rdrobust
RD bandwidth selection: msetwo
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Official rdrobust companion command; bandwidth selectors target different criteria.
Stata reference · R reference
rddensity x
rddensity::rddensity(x)
rddensity
Density continuity at the treatment threshold
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Tests density continuity, not the RD identification assumptions as a whole.
Stata reference · R reference
rddensity x, h(.4 .4)
rddensity::rddensity(x, h = c(.4, .4))
rddensity
Density continuity with fixed bandwidths
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Tests density continuity, not the RD identification assumptions as a whole.
Stata reference · R reference
rddensity x, p(3)
rddensity::rddensity(x, p = 3)
rddensity
Cubic local-polynomial density discontinuity
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Tests density continuity, not the RD identification assumptions as a whole.
Stata reference · R reference
rdrobust y x
rdrobust::rdrobust(y, x)
rdrobust
Sharp local-linear RD
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. User-written Stata rdrobust command. Match version, bandwidth, kernel and variance settings; no finite-fixture cross-software parity claim.
Stata reference · R reference
rdrobust y x, bwselect(cerrd)
rdrobust::rdrobust(y, x, bwselect = "cerrd")
rdrobust
Coverage-error-optimal RD bandwidth
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. User-written Stata rdrobust command. Match version, bandwidth, kernel and variance settings; no finite-fixture cross-software parity claim.
Stata reference · R reference
rdrobust y x, bwselect(msetwo)
rdrobust::rdrobust(y, x, bwselect = "msetwo")
rdrobust
Separate MSE-optimal bandwidths by side
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. User-written Stata rdrobust command. Match version, bandwidth, kernel and variance settings; no finite-fixture cross-software parity claim.
Stata reference · R reference
rdrobust y x, cluster(cluster)
rdrobust::rdrobust(y, x, cluster = cluster)
rdrobust
Cluster-robust RD inference
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. User-written Stata rdrobust command. Match version, bandwidth, kernel and variance settings; no finite-fixture cross-software parity claim.
Stata reference · R reference
rdrobust y x, covs(z)
rdrobust::rdrobust(y, x, covs = z)
rdrobust
Covariate-adjusted RD
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. User-written Stata rdrobust command. Match version, bandwidth, kernel and variance settings; no finite-fixture cross-software parity claim.
Stata reference · R reference
rdrobust y x, fuzzy(treat)
rdrobust::rdrobust(y, x, fuzzy = treat)
rdrobust
Fuzzy regression discontinuity
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Requires an exclusion restriction, a treatment-probability discontinuity and a suitable monotonicity assumption.
Stata reference · R reference
rdrobust y x, h(.4)
rdrobust::rdrobust(y, x, h = .4)
rdrobust
RD with fixed symmetric bandwidth
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. User-written Stata rdrobust command. Match version, bandwidth, kernel and variance settings; no finite-fixture cross-software parity claim.
Stata reference · R reference
rdrobust y x, kernel(epanechnikov)
rdrobust::rdrobust(y, x, kernel = "epanechnikov")
rdrobust
RD with Epanechnikov kernel
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. User-written Stata rdrobust command. Match version, bandwidth, kernel and variance settings; no finite-fixture cross-software parity claim.
Stata reference · R reference
rdrobust y x, kernel(uniform)
rdrobust::rdrobust(y, x, kernel = "uniform")
rdrobust
RD with uniform kernel
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. User-written Stata rdrobust command. Match version, bandwidth, kernel and variance settings; no finite-fixture cross-software parity claim.
Stata reference · R reference
rdrobust y x, level(90)
rdrobust::rdrobust(y, x, level = 90)
rdrobust
RD with ninety-percent confidence intervals
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. User-written Stata rdrobust command. Match version, bandwidth, kernel and variance settings; no finite-fixture cross-software parity claim.
Stata reference · R reference
rdrobust y x, p(2)
rdrobust::rdrobust(y, x, p = 2)
rdrobust
Local-quadratic RD
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. User-written Stata rdrobust command. Match version, bandwidth, kernel and variance settings; no finite-fixture cross-software parity claim.
Stata reference · R reference
tebalance summarize
cobalt::bal.tab(w, un = TRUE)
cobalt
Covariate balance before and after weighting
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Standardization denominator and binary-variable scaling must be aligned.
Stata reference · R reference
teffects aipw (y x z) (treat x z)
{ ps <- stats::fitted(stats::glm(treat ~ x + z, data, family = stats::binomial())); m0 <- stats::predict(stats::lm(y ~ x + z, data, subset = treat == 0), data); m1 <- stats::predict(stats::lm(y ~ x + z, data, subset = treat == 1), data); mean(m1 - m0 + data$treat * (data$y - m1) / ps - (1 - data$treat) * (data$y - m0) / (1 - ps)) }
stats
Augmented inverse-probability ATE point estimate
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. No standard errors; double robustness still requires overlap and identifying assumptions.
Stata reference · R reference
teffects ipw (y) (treat x z)
WeightIt::weightit(treat ~ x + z, data = data, method = "glm", estimand = "ATE")
WeightIt
Propensity-score weights targeting ATE
Fixed workflow; adapt the named data columns explicitly. Computes weights only, not treatment effects or standard errors. ATO and ATC are alternative target populations, not Stata teffects defaults.
Stata reference · R reference
teffects ipw (y) (treat x z)
WeightIt::weightit(treat ~ x + z, data = data, method = "glm", estimand = "ATC")
WeightIt
Propensity-score weights targeting ATC
Fixed workflow; adapt the named data columns explicitly. Computes weights only, not treatment effects or standard errors. ATO and ATC are alternative target populations, not Stata teffects defaults.
Stata reference · R reference
teffects ipw (y) (treat x z)
WeightIt::weightit(treat ~ x + z, data = data, method = "glm", estimand = "ATO")
WeightIt
Propensity-score weights targeting ATO
Fixed workflow; adapt the named data columns explicitly. Computes weights only, not treatment effects or standard errors. ATO and ATC are alternative target populations, not Stata teffects defaults.
Stata reference · R reference
teffects ipw (y) (treat x z)
{ w <- WeightIt::weightit(treat ~ x + z, data = data, method = "glm", estimand = "ATE")$weights; weighted.mean(data$y[data$treat == 1], w[data$treat == 1]) - weighted.mean(data$y[data$treat == 0], w[data$treat == 0]) }
WeightIt
Normalized IPW point effect for ATE
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Point estimate only; outcome-free weighting assumes conditional exchangeability and overlap. Weight-estimation uncertainty is not quantified.
Stata reference · R reference
teffects ipw (y) (treat x z) , atet
WeightIt::weightit(treat ~ x + z, data = data, method = "glm", estimand = "ATT")
WeightIt
Propensity-score weights targeting ATT
Fixed workflow; adapt the named data columns explicitly. Computes weights only, not treatment effects or standard errors. ATO and ATC are alternative target populations, not Stata teffects defaults.
Stata reference · R reference
teffects ipw (y) (treat x z) , atet
{ w <- WeightIt::weightit(treat ~ x + z, data = data, method = "glm", estimand = "ATT")$weights; weighted.mean(data$y[data$treat == 1], w[data$treat == 1]) - weighted.mean(data$y[data$treat == 0], w[data$treat == 0]) }
WeightIt
Normalized IPW point effect for ATT
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Point estimate only; outcome-free weighting assumes conditional exchangeability and overlap. Weight-estimation uncertainty is not quantified.
Stata reference · R reference
teffects ipwra (y x z) (treat x z)
{ ps <- stats::fitted(stats::glm(treat ~ x + z, data, family = stats::binomial())); data$w <- ifelse(data$treat == 1, 1 / ps, 1 / (1 - ps)); m0 <- stats::predict(stats::lm(y ~ x + z, data, subset = treat == 0, weights = w), data); m1 <- stats::predict(stats::lm(y ~ x + z, data, subset = treat == 1, weights = w), data); mean(m1 - m0) }
stats
Inverse-probability-weighted outcome-regression ATE
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Point estimation only; Stata jointly computes the estimating-equation variance.
Stata reference · R reference
teffects nnmatch (y x z) (treat), atet
MatchIt::matchit(treat ~ x + z, data = data, method = "nearest", distance = "mahalanobis", replace = TRUE, estimand = "ATT")
MatchIt
Mahalanobis nearest-neighbor preprocessing
Matches with replacement, as teffects does. MatchIt returns preprocessing weights and matches, not the treatment-effect estimate; tie handling, distance conventions, bias correction and Abadie-Imbens standard errors require separate alignment.
Stata reference · R reference
teffects psmatch (y) (treat x z), nneighbor(1) atet
MatchIt::matchit(treat ~ x + z, data = data, method = "nearest", distance = "glm", ratio = 1, replace = TRUE, estimand = "ATT")
MatchIt
One-to-one nearest propensity-score matching
Matches with replacement, as teffects does. MatchIt returns preprocessing weights and matches, not the treatment-effect estimate; tie handling, distance conventions, bias correction and Abadie-Imbens standard errors require separate alignment.
Stata reference · R reference
teffects psmatch (y) (treat x z), nneighbor(1) atet
MatchIt::matchit(treat ~ x + z, data = data, method = "nearest", distance = "glm", ratio = 1, replace = TRUE, estimand = "ATT")
MatchIt
Matching with replacement
Fixed workflow; adapt the named data columns explicitly. Preprocessing only; MatchIt does not reproduce teffects matching bias correction or Abadie-Imbens standard errors.
Stata reference · R reference
teffects psmatch (y) (treat x z), nneighbor(2) atet
MatchIt::matchit(treat ~ x + z, data = data, method = "nearest", distance = "glm", ratio = 2, replace = TRUE, estimand = "ATT")
MatchIt
One-to-two nearest propensity-score matching
Matches with replacement, as teffects does. MatchIt returns preprocessing weights and matches, not the treatment-effect estimate; tie handling, distance conventions, bias correction and Abadie-Imbens standard errors require separate alignment.
Stata reference · R reference
teffects ra (y x z) (treat)
{ fit0 <- stats::lm(y ~ x + z, data, subset = treat == 0); fit1 <- stats::lm(y ~ x + z, data, subset = treat == 1); mean(stats::predict(fit1, data) - stats::predict(fit0, data)) }
stats
Regression-adjustment average treatment effect
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Point-estimate g-computation under correctly specified potential-outcome models; no causal identification is established by fitting alone.
Stata reference · R reference
teffects ra (y x z) (treat), atet
{ fit0 <- stats::lm(y ~ x + z, data, subset = treat == 0); fit1 <- stats::lm(y ~ x + z, data, subset = treat == 1); treated <- data[data$treat == 1, ]; mean(stats::predict(fit1, treated) - stats::predict(fit0, treated)) }
stats
Regression-adjustment effect among treated units
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Averages counterfactual differences over the treated covariate distribution.
Stata reference · R reference
teoverlap
{ ps <- stats::fitted(stats::glm(treat ~ x + z, data, family = stats::binomial())); lapply(split(ps, data$treat), function(v) stats::quantile(v, c(0, .05, .5, .95, 1))) }
stats
Propensity-score overlap summary by treatment
Fixed workflow; adapt the named data columns explicitly. Numeric overlap diagnostic; no density plot or automatic trimming.
Stata reference · R reference
xtdidregress (y x) (treated), group(id) time(time)
fixest::feols(y ~ treated + x | id + time, data = data, vcov = ~id, nthreads = 1)
fixest
Panel difference-in-differences with unit and period fixed effects
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Homogeneous-effect two-group design with parallel trends and no anticipation. Under staggered timing and heterogeneous effects, TWFE is not a replacement for modern cohort-specific estimators; covariance finite-sample conventions can differ.
Stata reference · R reference

Panel data

Stata R Purpose, qualifications and sources
hausman fixed random
plm::phtest(fe, re)
plm
Hausman comparison of fixed and random effects
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Requires same regressors and compatible covariance assumptions.
Stata reference · R reference
xtcloglog binary x, re
lme4::glmer(binary ~ x + (1 | id), data = data, family = stats::binomial(link = "cloglog"), nAGQ = 12)
lme4
Random-intercept panel cloglog
Differs from Stata: Uses normal panel random intercepts and 12-point adaptive quadrature, matching Stata intpoints(12). Quadrature adaptation and convergence criteria remain package-specific.
Stata reference · R reference
xtdpd y L.y x, div(x) dgmmiv(y, lagrange(2 3))
{ plm <- plm::plm; plm::pgmm(y ~ lag(y, 1) + x | lag(y, 2:3), data = pd, effect = "individual", model = "onestep", transformation = "d", collapse = TRUE) }
plm
One-step difference GMM for a dynamic panel
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Supports the standard difference-GMM subset, with deliberately collapsed instruments. Stata xtdpd supports richer error processes; align instruments, initial weight matrices and finite-sample corrections before comparing.
Stata reference · R reference
xtdpdsys y x, maxldep(3)
{ plm <- plm::plm; plm::pgmm(y ~ lag(y, 1) + x | lag(y, 2:3), data = pd, effect = "individual", model = "onestep", transformation = "ld", collapse = TRUE) }
plm
System GMM with level and differenced equations
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Additional level moment conditions require stronger initial-condition assumptions. Instrument collapsing, instrument ranges and weighting differ unless explicitly matched; no blanket parity with xtdpdsys defaults.
Stata reference · R reference
xtgee binary x, family( binomial ) corr( ar1 )
geepack::geeglm(binary ~ x, id = id, waves = time, data = data, family = stats::binomial(), corstr = "ar1")
geepack
binomial GEE with ar1 working correlation
Differs from Stata: Keep rows sorted in contiguous panels. geeglm defaults to sandwich robust standard errors (std.err="san.se"), corresponding to xtgee, vce(robust); Stata defaults to conventional model-based standard errors. Scale estimation, small-sample adjustments and correlation estimation may still differ.
Stata reference · R reference
xtgee binary x, family( binomial ) corr( exchangeable )
geepack::geeglm(binary ~ x, id = id, waves = time, data = data, family = stats::binomial(), corstr = "exchangeable")
geepack
binomial GEE with exchangeable working correlation
Differs from Stata: Keep rows sorted in contiguous panels. geeglm defaults to sandwich robust standard errors (std.err="san.se"), corresponding to xtgee, vce(robust); Stata defaults to conventional model-based standard errors. Scale estimation, small-sample adjustments and correlation estimation may still differ.
Stata reference · R reference
xtgee binary x, family( binomial ) corr( independence )
geepack::geeglm(binary ~ x, id = id, waves = time, data = data, family = stats::binomial(), corstr = "independence")
geepack
binomial GEE with independence working correlation
Differs from Stata: Keep rows sorted in contiguous panels. geeglm defaults to sandwich robust standard errors (std.err="san.se"), corresponding to xtgee, vce(robust); Stata defaults to conventional model-based standard errors. Scale estimation, small-sample adjustments and correlation estimation may still differ.
Stata reference · R reference
xtgee count x, family( poisson ) corr( ar1 )
geepack::geeglm(count ~ x, id = id, waves = time, data = data, family = stats::poisson(), corstr = "ar1")
geepack
poisson GEE with ar1 working correlation
Differs from Stata: Keep rows sorted in contiguous panels. geeglm defaults to sandwich robust standard errors (std.err="san.se"), corresponding to xtgee, vce(robust); Stata defaults to conventional model-based standard errors. Scale estimation, small-sample adjustments and correlation estimation may still differ.
Stata reference · R reference
xtgee count x, family( poisson ) corr( exchangeable )
geepack::geeglm(count ~ x, id = id, waves = time, data = data, family = stats::poisson(), corstr = "exchangeable")
geepack
poisson GEE with exchangeable working correlation
Differs from Stata: Keep rows sorted in contiguous panels. geeglm defaults to sandwich robust standard errors (std.err="san.se"), corresponding to xtgee, vce(robust); Stata defaults to conventional model-based standard errors. Scale estimation, small-sample adjustments and correlation estimation may still differ.
Stata reference · R reference
xtgee count x, family( poisson ) corr( independence )
geepack::geeglm(count ~ x, id = id, waves = time, data = data, family = stats::poisson(), corstr = "independence")
geepack
poisson GEE with independence working correlation
Differs from Stata: Keep rows sorted in contiguous panels. geeglm defaults to sandwich robust standard errors (std.err="san.se"), corresponding to xtgee, vce(robust); Stata defaults to conventional model-based standard errors. Scale estimation, small-sample adjustments and correlation estimation may still differ.
Stata reference · R reference
xtgee y x, family( gaussian ) corr( ar1 )
geepack::geeglm(y ~ x, id = id, waves = time, data = data, family = stats::gaussian(), corstr = "ar1")
geepack
gaussian GEE with ar1 working correlation
Differs from Stata: Keep rows sorted in contiguous panels. geeglm defaults to sandwich robust standard errors (std.err="san.se"), corresponding to xtgee, vce(robust); Stata defaults to conventional model-based standard errors. Scale estimation, small-sample adjustments and correlation estimation may still differ.
Stata reference · R reference
xtgee y x, family( gaussian ) corr( exchangeable )
geepack::geeglm(y ~ x, id = id, waves = time, data = data, family = stats::gaussian(), corstr = "exchangeable")
geepack
gaussian GEE with exchangeable working correlation
Differs from Stata: Keep rows sorted in contiguous panels. geeglm defaults to sandwich robust standard errors (std.err="san.se"), corresponding to xtgee, vce(robust); Stata defaults to conventional model-based standard errors. Scale estimation, small-sample adjustments and correlation estimation may still differ.
Stata reference · R reference
xtgee y x, family( gaussian ) corr( independence )
geepack::geeglm(y ~ x, id = id, waves = time, data = data, family = stats::gaussian(), corstr = "independence")
geepack
gaussian GEE with independence working correlation
Differs from Stata: Keep rows sorted in contiguous panels. geeglm defaults to sandwich robust standard errors (std.err="san.se"), corresponding to xtgee, vce(robust); Stata defaults to conventional model-based standard errors. Scale estimation, small-sample adjustments and correlation estimation may still differ.
Stata reference · R reference
xtgls y x z, panels(heteroskedastic) igls
nlme::gls(y ~ x + z, data = data, weights = nlme::varIdent(form = ~1 | id), method = "ML")
nlme
Group-heteroskedastic panel GLS by maximum likelihood
Fixed workflow; adapt the named data columns explicitly. Common slopes with independent residuals and group-specific residual variances; likelihood, variance normalization and convergence criteria can differ.
Stata reference · R reference
xthtaylor y x1 x2 a b, endog(x2 b) constant(a b)
plm::plm(y ~ x1 + x2 + a + b | x1 + a | x2, data = data, index = c("id", "time"), random.method = "ht", model = "random", inst.method = "baltagi")
plm
Hausman-Taylor model with time-varying and invariant endogenous covariates
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. The three-part R formula explicitly separates exogenous covariates and time-varying endogenous covariates. Identification of invariant endogenous effects requires sufficient exogenous time-varying instruments; these classifications need substantive justification.
Stata reference · R reference
xtivreg y z (x = instrument), fe
plm::plm(y ~ x + z | instrument + z, data = pd, model = "within")
plm
Fixed-effects instrumental-variable regression
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Instrument validity must be justified substantively; this fixture only verifies execution.
Stata reference · R reference
xtlogit binary x, fe
{ coxph <- survival::coxph; survival::clogit(binary ~ x + survival::strata(id), data = data) }
survival
Conditional fixed-effects logistic regression
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Conditions out group intercepts; groups without outcome variation contribute no coefficient information.
Stata reference · R reference
xtpcse y x z, correlation(independent)
{ fit <- plm::plm(y ~ x + z, data = pd, model = "pooling"); lmtest::coeftest(fit, vcov. = plm::vcovBK(fit, type = "HC0", cluster = "time")) }
plm
Beck-Katz panel-corrected covariance
Differs from Stata: vcovBK(cluster="time") allows contemporaneous cross-panel covariance, as required for PCSE. Balancedness, pairwise missing-data treatment, finite-sample normalization and reference tests can still differ from xtpcse.
Stata reference · R reference
xtpoisson count x, re normal
lme4::glmer(count ~ x + (1 | id), data = data, family = stats::poisson(link = "log"), nAGQ = 12)
lme4
Random-intercept panel Poisson
Differs from Stata: Uses normal panel random intercepts and 12-point adaptive quadrature, matching the Stata integration-point default. xtpoisson requires re normal for this distribution; its plain re default is gamma. Quadrature adaptation and convergence criteria remain package-specific.
Stata reference · R reference
xtprobit binary x, re
lme4::glmer(binary ~ x + (1 | id), data = data, family = stats::binomial(link = "probit"), nAGQ = 12)
lme4
Random-intercept panel probit
Differs from Stata: Uses normal panel random intercepts and 12-point adaptive quadrature, matching Stata intpoints(12). Quadrature adaptation and convergence criteria remain package-specific.
Stata reference · R reference
xtrc y x z
nlme::lme(y ~ x + z, random = ~ x + z | id, data = data, method = "ML")
nlme
Random-coefficient panel model workflow
All three coefficients (intercept, x and z) vary by panel. nlme fits a Gaussian mixed model by ML; xtrc uses Swamy random-coefficient GLS, so the estimators and covariance estimates differ.
Stata reference · R reference
xtreg y x z i.time, fe
plm::plm(y ~ x + z, data = pd, model = "within", effect = "twoways")
plm
Individual and time fixed effects
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. First-difference and pooled rows are explicit benchmarks; match estimator and effects.
Stata reference · R reference
xtreg y x z, be
plm::plm(y ~ x + z, data = pd, model = "between", effect = "individual")
plm
Between-unit regression
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. First-difference and pooled rows are explicit benchmarks; match estimator and effects.
Stata reference · R reference
xtreg y x z, fe
plm::plm(y ~ x + z, data = pd, model = "within", effect = "individual")
plm
Individual fixed effects
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. First-difference and pooled rows are explicit benchmarks; match estimator and effects.
Stata reference · R reference
xtreg y x z, fe
plm::plm(y ~ x + z, data = pd, model = "within", effect = "individual")
plm
Fit a within-panel fixed-effects regression
Both commands fit individual fixed effects using the within transformation. plm reports the transformed-model coefficient vector without Stata reported intercept; residual degrees of freedom and covariance scaling must be aligned separately.
Stata reference · R reference
xtreg y x z, fe vce(cluster id)
{ V <- plm::vcovHC(fit, method = "arellano", type = "HC1", cluster = "group"); lmtest::coeftest(fit, vcov. = V) }
plm
Cluster-robust panel standard errors
Differs from Stata: Stata xtreg, fe vce(robust) equals vce(cluster id). plm HC1 uses N/(N-K) with K counting within-model coefficients and coeftest uses residual degrees of freedom; Stata also applies its cluster correction and uses G-1 reference degrees of freedom. These standard errors and p-values are not exact Stata finite-sample parity.
Stata reference · R reference
xtreg y x z, fe vce(robust)
{ V <- plm::vcovHC(fit, method = "arellano", type = "HC1", cluster = "group"); lmtest::coeftest(fit, vcov. = V) }
plm
Cluster-robust within-panel standard errors
Differs from Stata: Stata xtreg, fe vce(robust) equals vce(cluster id). plm HC1 uses N/(N-K) with K counting within-model coefficients and coeftest uses residual degrees of freedom; Stata also applies its cluster correction and uses G-1 reference degrees of freedom. These standard errors and p-values are not exact Stata finite-sample parity.
Stata reference · R reference
xtreg y x z, pa corr(independent)
plm::plm(y ~ x + z, data = pd, model = "pooling", effect = "individual")
plm
Pooled panel regression benchmark
Under independent working correlation, population-averaged Gaussian GEE and pooled OLS have the same coefficients. xtreg, pa defaults to conventional model-based GEE covariance (not robust unless requested); pooled plm uses OLS residual scaling, so reported standard errors can differ.
Stata reference · R reference
xtreg y x z, re
plm::plm(y ~ x + z, data = pd, model = "random", effect = "individual")
plm
Random-effects panel regression
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. First-difference and pooled rows are explicit benchmarks; match estimator and effects.
Stata reference · R reference
xtreg y x z, re
plm::plm(y ~ x + z, data = pd, model = "random", random.method = "swar")
plm
Random effects with swar variance components
Fixed workflow; adapt the named data columns explicitly. These are named alternative variance-component estimators; only matching methods justify comparing estimates.
Stata reference · R reference
xtreg y x z, re
plm::plm(y ~ x + z, data = pd, model = "random", random.method = "walhus")
plm
Random effects with walhus variance components
Walhus is an R alternative variance-component estimator with no corresponding xtreg option. Stata xtreg, re uses its default estimator or sa for Swamy-Arora; the Stata line does not select Walhus and numerical parity is not claimed.
Stata reference · R reference
xtreg y x z, re
plm::plm(y ~ x + z, data = pd, model = "random", random.method = "amemiya")
plm
Random effects with amemiya variance components
Amemiya is an R alternative variance-component estimator with no corresponding xtreg option. Stata xtreg, re uses its default estimator or sa for Swamy-Arora; the Stata line does not select Amemiya and numerical parity is not claimed.
Stata reference · R reference
xtreg y x z, re
plm::plm(y ~ x + z, data = pd, model = "random", random.method = "nerlove")
plm
Random effects with nerlove variance components
Nerlove is an R alternative variance-component estimator with no corresponding xtreg option. Stata xtreg, re uses its default estimator or sa for Swamy-Arora; the Stata line does not select Nerlove and numerical parity is not claimed.
Stata reference · R reference
xtregar y x z, re
nlme::lme(y ~ x + z, random = ~1 | id, correlation = nlme::corAR1(form = ~time | id), data = data, method = "ML")
nlme
Random intercept with AR(1) residual correlation
Fixed workflow; adapt the named data columns explicitly. Likelihood-based mixed-model workflow differs from xtregar's estimator.
Stata reference · R reference
xtscc y x z, fe lag(2)
{ V <- plm::vcovSCC(fit, type = "HC1", maxlag = 2); lmtest::coeftest(fit, vcov. = V) }
plm
Driscoll-Kraay covariance
Differs from Stata: Requires the community command xtscc (ssc install xtscc); xtreg has no vce(dkraay) option. Both use a within estimator with lag-2 Driscoll-Kraay covariance; finite-sample scaling and reference degrees of freedom differ.
Stata reference · R reference
xtreg y x z, re
xttest0
plm::plmtest(plm::plm(y ~ x + z, data = pd, model = "pooling"), type = "bp", effect = "individual")
plm
Breusch-Pagan test of individual random effects
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stata's boundary-adjusted mixture distribution can differ from plm's chi-square reference.
Stata reference · R reference
xtunitroot fisher y, dfuller lags(1)
plm::purtest(pd$y, test = "madwu", exo = "intercept", lags = 1, pmax = 1)
plm
Panel unit-root test: madwu
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Hadri reverses the null to stationarity; deterministic terms and lag rules must match.
Stata reference · R reference
xtunitroot hadri y, robust
plm::purtest(pd$y, test = "hadri", exo = "intercept", Hcons = TRUE)
plm
Panel unit-root test: hadri
Differs from Stata: The null is panel stationarity. Hcons=TRUE selects the heteroskedasticity-robust Hadri statistic, corresponding to Stata robust; plm ignores lag selections for Hadri and provides no Bartlett HAC kernel correction.
Stata reference · R reference
xtunitroot ips y, lags(1)
plm::purtest(pd$y, test = "ips", exo = "intercept", lags = 1, pmax = 1)
plm
Panel unit-root test: ips
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Hadri reverses the null to stationarity; deterministic terms and lag rules must match.
Stata reference · R reference
xtunitroot llc y, lags(1)
plm::purtest(pd$y, test = "levinlin", exo = "intercept", lags = 1, pmax = 1)
plm
Panel unit-root test: levinlin
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Hadri reverses the null to stationarity; deterministic terms and lag rules must match.
Stata reference · R reference

Time series and forecasting

Stata R Purpose, qualifications and sources
ac y, lags(12)
stats::acf(y, lag.max = 12, plot = FALSE)
stats
Autocorrelation function
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R returns numeric correlations; request plotting separately.
Stata reference · R reference
arch y, arch(1) garch(1) noconstant
tseries::garch(as.numeric(y), order = c(1, 1), trace = FALSE)
tseries
GARCH(1,1) conditional-variance model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Fit a mean model separately; optimization and initialization differ.
Stata reference · R reference
arch y, arch(1) noconstant
tseries::garch(as.numeric(y), order = c(0, 1), trace = FALSE)
tseries
ARCH(1) conditional-variance model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. tseries::garch models zero-mean observations; remove or explicitly model the conditional mean first.
Stata reference · R reference
arfima y, ar(1) ma(1)
fracdiff::fracdiff(y, nar = 1, nma = 1)
fracdiff
Fractionally integrated ARMA estimation
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. fracdiff uses approximate likelihood and a different MA sign convention.
Stata reference · R reference
arfimasoc y, maxar(1) maxma(1)
{ grid <- expand.grid(p = 0:1, q = 0:1); grid$AIC <- mapply(function(p, q) { f <- fracdiff::fracdiff(y, nar = p, nma = q); -2 * f$log.likelihood + 2 * (p + q + 2) }, grid$p, grid$q); grid }
fracdiff
Fractional-ARMA order comparison
Fixed workflow; adapt the named data columns explicitly. Approximate-likelihood order-selection workflow; no numerical parity claim.
Stata reference · R reference
arima y x, arima(1,0,0)
stats::arima(y, order = c(1, 0, 0), xreg = x)
stats
ARMAX with external regressor
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Parameterization, initialization and likelihood conventions differ; compare selected model, not default output.
Stata reference · R reference
arima y, arima(0,0,0) sarima(0,1,1,4)
stats::arima(y, order = c(0, 0, 0), seasonal = list(order = c(0, 1, 1), period = 4))
stats
Seasonally differenced moving average
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Parameterization, initialization and likelihood conventions differ; compare selected model, not default output.
Stata reference · R reference
arima y, arima(0,0,0) sarima(1,0,0,4)
stats::arima(y, order = c(0, 0, 0), seasonal = list(order = c(1, 0, 0), period = 4))
stats
Seasonal autoregression
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Parameterization, initialization and likelihood conventions differ; compare selected model, not default output.
Stata reference · R reference
arima y, arima(0,0,1)
stats::arima(y, order = c(0, 0, 1))
stats
MA(1) with intercept
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Parameterization, initialization and likelihood conventions differ; compare selected model, not default output.
Stata reference · R reference
arima y, arima(0,1,1)
stats::arima(y, order = c(0, 1, 1))
stats
Integrated moving-average model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Parameterization, initialization and likelihood conventions differ; compare selected model, not default output.
Stata reference · R reference
arima y, arima(1,0,0)
stats::arima(y, order = c(1, 0, 0))
stats
AR(1) with intercept
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Parameterization, initialization and likelihood conventions differ; compare selected model, not default output.
Stata reference · R reference
arima y, arima(1,0,0) diffuse
stats::arima(y, order = c(1, 0, 0), method = "ML", SSinit = "Rossignol2011")
stats
State-space maximum-likelihood estimation
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Parameterization, initialization and likelihood conventions differ; compare selected model, not default output.
Stata reference · R reference
arima y, arima(1,0,0) noconstant
stats::arima(y, order = c(1, 0, 0), include.mean = FALSE)
stats
Zero-mean autoregression
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Parameterization, initialization and likelihood conventions differ; compare selected model, not default output.
Stata reference · R reference
arima y, arima(1,0,1)
stats::arima(y, order = c(1, 0, 1))
stats
ARMA(1,1)
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Parameterization, initialization and likelihood conventions differ; compare selected model, not default output.
Stata reference · R reference
arima y, arima(1,0,1)
stats::arima(y, order = c(1, 0, 1), method = "ML")
stats
ARMA estimation using ML
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Explicit likelihood setting avoids relying on R's default CSS-ML initialization.
Stata reference · R reference
arima y, arima(1,0,1) // conditional least-squares alternative
stats::arima(y, order = c(1, 0, 1), method = "CSS")
stats
ARMA estimation using CSS
Fixed workflow; adapt the named data columns explicitly. Conditional sum of squares is a workflow alternative, not Stata's default likelihood.
Stata reference · R reference
arima y, arima(1,1,0)
stats::arima(y, order = c(1, 1, 0))
stats
ARIMA with first difference
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Parameterization, initialization and likelihood conventions differ; compare selected model, not default output.
Stata reference · R reference
arimasoc y, maxar(2) maxma(2)
{ grid <- expand.grid(p = 0:2, q = 0:2); grid$AIC <- mapply(function(p, q) stats::AIC(stats::arima(y, order = c(p, 0, q), method = "ML")), grid$p, grid$q); grid }
stats
ARMA information-criterion grid
Fixed workflow; adapt the named data columns explicitly. Comparable-sample model-selection workflow; R and Stata likelihood constants may differ.
Stata reference · R reference
corrgram y, lags(8)
list(ac = stats::acf(y, lag.max = 8, plot = FALSE), pac = stats::pacf(y, lag.max = 8, plot = FALSE))
stats
Autocorrelation and partial-autocorrelation table
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R returns numeric correlations; request plotting separately.
Stata reference · R reference
cumsp y
{ sp <- stats::spectrum(y, plot = FALSE, taper = 0); data.frame(frequency = sp$freq, cumulative = cumsum(sp$spec) / sum(sp$spec)) }
stats
Cumulative spectral distribution
Fixed workflow; adapt the named data columns explicitly. Computes curve data; confidence bands are not included.
Stata reference · R reference
dfgls y, maxlag(4)
urca::ur.ers(y, type = "DF-GLS", model = "trend", lag.max = 4)
urca
DF-GLS unit-root test with trend
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Lag-selection and finite-sample critical values may differ.
Stata reference · R reference
dfgls y, maxlag(4) notrend
urca::ur.ers(y, type = "DF-GLS", model = "constant", lag.max = 4)
urca
DF-GLS unit-root test with constant
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Lag-selection and finite-sample critical values may differ.
Stata reference · R reference
dfuller y, lags(0)
urca::ur.df(y, type = "drift", lags = 0)
urca
ADF unit-root test with drift and 0 augmentation lags
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match deterministic terms, sample window and lag selection; critical-value implementations can differ.
Stata reference · R reference
dfuller y, lags(0) noconstant
urca::ur.df(y, type = "none", lags = 0)
urca
ADF unit-root test with none and 0 augmentation lags
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match deterministic terms, sample window and lag selection; critical-value implementations can differ.
Stata reference · R reference
dfuller y, lags(0) trend
urca::ur.df(y, type = "trend", lags = 0)
urca
ADF unit-root test with trend and 0 augmentation lags
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match deterministic terms, sample window and lag selection; critical-value implementations can differ.
Stata reference · R reference
dfuller y, lags(2)
urca::ur.df(y, type = "drift", lags = 2)
urca
ADF unit-root test with drift and 2 augmentation lags
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match deterministic terms, sample window and lag selection; critical-value implementations can differ.
Stata reference · R reference
dfuller y, lags(2) noconstant
urca::ur.df(y, type = "none", lags = 2)
urca
ADF unit-root test with none and 2 augmentation lags
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match deterministic terms, sample window and lag selection; critical-value implementations can differ.
Stata reference · R reference
dfuller y, lags(2) trend
urca::ur.df(y, type = "trend", lags = 2)
urca
ADF unit-root test with trend and 2 augmentation lags
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match deterministic terms, sample window and lag selection; critical-value implementations can differ.
Stata reference · R reference
fcast compute pred, step(8)
{ out <- matrix(NA_real_, 8, 2); last <- tail(Y, 1); intercept <- stats::coef(fit)[1, ]; for (h in 1:8) { last <- matrix(intercept + drop(A %*% drop(last)), nrow = 1); out[h, ] <- last }; colnames(out) <- colnames(Y); out }
stats
Iterated bivariate VAR point forecasts
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Point forecasts only; no system forecast-error covariance or interval calculation.
Stata reference · R reference
forecast solve, begin(161)
forecast::forecast(fit, h = 8)
forecast
Eight-period ARIMA forecast
Fixed workflow; adapt the named data columns explicitly. Single-equation forecasting workflow; forecast system identities are not translated.
Stata reference · R reference
forecast solve, begin(161) periods(8) simulate(errors, statistic(stddev, prefix(sd_)))
forecast::forecast(fit, h = 8, level = 90)
forecast
Forecast with ninety-percent prediction intervals
Fixed workflow; adapt the named data columns explicitly. Single-equation forecasting workflow; forecast system identities are not translated. R produces analytic 90% prediction intervals; the Stata example instead simulates forecast standard deviations, requiring a separate interval calculation.
Stata reference · R reference
forecast solve, begin(161) static
stats::fitted(forecast::Arima(y, order = c(1, 0, 0)))
forecast
One-step fitted values from ARIMA
Fixed workflow; adapt the named data columns explicitly. In-sample one-step prediction workflow; Stata's forecast model setup is separate.
Stata reference · R reference
irf create model, step(8)
{ powers <- vector("list", 9); powers[[1]] <- diag(2); for (h in 2:9) powers[[h]] <- powers[[h - 1]] %*% A; powers }
base
Reduced-form VAR(1) impulse-response matrices
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Unit reduced-form innovation responses; orthogonalized structural responses require an identification scheme.
Stata reference · R reference
irf create model, step(8) // orthogonalized responses
{ impact <- t(chol(crossprod(stats::residuals(fit)) / stats::nobs(fit))); powers <- vector("list", 9); powers[[1]] <- impact; for (h in 2:9) powers[[h]] <- A %*% powers[[h - 1]]; powers }
base
Cholesky-orthogonalized VAR responses
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Recursive ordering is y then x; covariance divisor and identifying assumptions matter.
Stata reference · R reference
ivlpirf y, endogenous(x = z) step(8) lags(1)
vapply(0:8, function(h) { i <- 2:(nrow(data) - h); d <- data.frame(outcome = data$y[i + h], impulse = data$x[i], Ly = data$y[i - 1], instrument = data$z[i]); unname(stats::coef(AER::ivreg(outcome ~ impulse + Ly | instrument + Ly, data = d))[2]) }, numeric(1))
AER
Instrumental-variable local-projection point responses
Fixed workflow; adapt the named data columns explicitly. Horizonwise 2SLS workflow; instrument validity, normalization and HAC inference require separate decisions.
Stata reference · R reference
lpirf y, exog(x) step(8) lags(1)
vapply(0:8, function(h) { i <- 2:(nrow(data) - h); unname(stats::coef(stats::lm(data$y[i + h] ~ data$x[i] + data$y[i - 1] + data$x[i - 1]))[2]) }, numeric(1))
stats
Local-projection dynamic response to an external impulse
Fixed workflow; adapt the named data columns explicitly. Simple horizonwise point-estimation workflow; HAC inference and system restrictions must be added for research use.
Stata reference · R reference
newey y x, lag(4)
{ fit <- stats::lm(y ~ x, data = data); lmtest::coeftest(fit, vcov. = sandwich::NeweyWest(fit, lag = 4, prewhite = FALSE, adjust = TRUE)) }
sandwich
Newey-West HAC coefficient inference
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Explicit bandwidth, prewhitening and finite-sample correction; align those choices.
Stata reference · R reference
pac y, lags(12)
stats::pacf(y, lag.max = 12, plot = FALSE)
stats
Partial autocorrelation function
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R returns numeric correlations; request plotting separately.
Stata reference · R reference
pergram y
stats::spectrum(y, plot = FALSE, taper = 0, detrend = FALSE)
stats
Raw periodogram
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Normalization and default tapering can differ.
Stata reference · R reference
pperron y, lags(4)
urca::ur.pp(y, type = "Z-tau", model = "constant", use.lag = 4)
urca
Phillips-Perron Z-tau test with constant
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stata reports several statistics together; R selects one statistic. Kernel and deterministic terms must be matched.
Stata reference · R reference
pperron y, lags(4)
urca::ur.pp(y, type = "Z-alpha", model = "constant", use.lag = 4)
urca
Phillips-Perron Z-alpha test with constant
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stata reports several statistics together; R selects one statistic. Kernel and deterministic terms must be matched.
Stata reference · R reference
pperron y, lags(4) trend
urca::ur.pp(y, type = "Z-tau", model = "trend", use.lag = 4)
urca
Phillips-Perron Z-tau test with trend
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stata reports several statistics together; R selects one statistic. Kernel and deterministic terms must be matched.
Stata reference · R reference
pperron y, lags(4) trend
urca::ur.pp(y, type = "Z-alpha", model = "trend", use.lag = 4)
urca
Phillips-Perron Z-alpha test with trend
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stata reports several statistics together; R selects one statistic. Kernel and deterministic terms must be matched.
Stata reference · R reference
predict yhat, y dynamic(161)
stats::predict(fit, n.ahead = 8)
stats
Dynamic ARIMA forecast and standard errors
Fixed workflow; adapt the named data columns explicitly. Single-equation forecasting workflow; forecast system identities are not translated.
Stata reference · R reference
arima y, arima(1,0,0)
psdensity density, n(64)
{ phi <- unname(fit$coef["ar1"]); omega <- seq(0, pi, length.out = 64); data.frame(frequency = omega / (2 * pi), density = fit$sigma2 / (2 * pi * Mod(1 - phi * exp(-1i * omega))^2)) }
stats
Parametric AR(1) spectral density
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Frequency and density normalization conventions must be reconciled.
Stata reference · R reference
rolling _b, window(40) recursive: regress y x
t(vapply(40:nrow(data), function(i) stats::coef(stats::lm(y ~ x, data[seq_len(i), ])), numeric(2)))
stats
Expanding-window recursive regression
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Uses a fixed first observation and increasing estimation endpoint.
Stata reference · R reference
rolling _b, window(40): regress y x
zoo::rollapply(data, width = 40, FUN = function(z) stats::coef(stats::lm(y ~ x, data = as.data.frame(z))), by.column = FALSE, align = "right")
zoo
Rolling-window regression coefficients
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Output rows correspond to complete right-aligned windows; failures need explicit handling in production.
Stata reference · R reference
rolling sd=r(sd), window(20): summarize y
zoo::rollapply(y, width = 20, FUN = stats::sd, align = "right")
zoo
Rolling sample volatility
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Sample standard deviation, not model-implied conditional volatility.
Stata reference · R reference
sspace (level L.level L.slope, state noconstant) (slope L.slope, state noconstant) (y level, noconstant)
stats::StructTS(y, type = "trend")
stats
Local-linear-trend state-space model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Specific local-linear-trend model; initialization can differ.
Stata reference · R reference
sspace (level L.level, state noconstant) (y level, noconstant)
stats::StructTS(y, type = "level")
stats
Local-level state-space model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Specific local-level model equivalent; sspace supports a much wider model class.
Stata reference · R reference
tsfilter bk cycle = y, minperiod(6) maxperiod(32) smaorder(12)
{ K <- 12; j <- -K:K; low <- 2 * pi / 32; high <- 2 * pi / 6; w <- ifelse(j == 0, (high - low) / pi, (sin(high * j) - sin(low * j)) / (pi * j)); w <- w - mean(w); stats::filter(y, w, sides = 2) }
stats
Baxter-King approximate band-pass cycle
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Symmetric finite-order band-pass filter loses endpoint observations.
Stata reference · R reference
tsfilter hp cycle = y, smooth(1600) trend(trend)
{ n <- length(y); D <- diff(diag(n), differences = 2); trend <- drop(solve(diag(n) + 1600 * crossprod(D), as.numeric(y))); data.frame(trend = trend, cycle = as.numeric(y) - trend) }
base
Hodrick-Prescott trend and cycle decomposition
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Complete regular series; this direct penalized least-squares solution uses the two-sided HP filter.
Stata reference · R reference
tsreport, report
data.frame(previous = head(data$t, -1), next_time = tail(data$t, -1), gap = diff(data$t))[diff(data$t) != 1, ]
base
Locate missing time periods
Fixed workflow; adapt the named data columns explicitly. Assumes integer unit-spaced time; date calendars need the intended interval definition.
Stata reference · R reference
tssmooth exponential smooth = y, parms(.3)
stats::HoltWinters(y, alpha = .3, beta = FALSE, gamma = FALSE)
stats
Simple exponential smoothing
Fixed workflow; adapt the named data columns explicitly. Initial values, endpoints and trend formulations differ; align before comparing.
Stata reference · R reference
tssmooth hwinters smooth = y
stats::HoltWinters(y, gamma = FALSE)
stats
Holt trend smoothing workflow
Fixed workflow; adapt the named data columns explicitly. Initial values, endpoints and trend formulations differ; align before comparing.
Stata reference · R reference
tssmooth ma smooth = y, window(2 1 2)
stats::filter(y, rep(1 / 5, 5), sides = 2)
stats
Centered five-term moving average
Fixed workflow; adapt the named data columns explicitly. Initial values, endpoints and trend formulations differ; align before comparing.
Stata reference · R reference
tssmooth ma smooth = y, window(3 1 0)
stats::filter(y, rep(1 / 4, 4), sides = 1)
stats
Trailing four-term moving average
Fixed workflow; adapt the named data columns explicitly. Initial values, endpoints and trend formulations differ; align before comparing.
Stata reference · R reference
tssmooth nl smooth = y, smoother(3)
stats::runmed(as.numeric(y), k = 3, endrule = "median")
stats
Running-median nonlinear smoother
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Endpoint rules should be checked separately before comparing.
Stata reference · R reference
tssmooth shwinters smooth = y
stats::HoltWinters(y, seasonal = "additive")
stats
Additive seasonal Holt-Winters smoothing
Fixed workflow; adapt the named data columns explicitly. Initial values, endpoints and trend formulations differ; align before comparing.
Stata reference · R reference
ucm y, model(llevel)
stats::StructTS(y, type = "level")
stats
Unobserved components: level
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R supports selected structural models; Stata ucm permits additional components and constraints.
Stata reference · R reference
ucm y, model(lltrend)
stats::StructTS(y, type = "trend")
stats
Unobserved components: trend
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R supports selected structural models; Stata ucm permits additional components and constraints.
Stata reference · R reference
ucm y, model(lltrend) seasonal(4)
stats::StructTS(y, type = "BSM")
stats
Unobserved components: BSM
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R supports selected structural models; Stata ucm permits additional components and constraints.
Stata reference · R reference
var y x, lags(1)
stats::lm(cbind(y, x) ~ Ly + Lx, data = lagged)
stats
Unrestricted bivariate VAR(1) by equation OLS
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Coefficient equivalent for an unrestricted common-sample VAR; system covariance reporting differs.
Stata reference · R reference
var y x, lags(1) exog(trend)
stats::lm(cbind(y, x) ~ Ly + Lx + seq_len(nrow(lagged)), data = lagged)
stats
VAR with deterministic time trend
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Trend origin affects intercepts; compare the same sample and trend indexing.
Stata reference · R reference
var y x, lags(1) noconstant
stats::lm(cbind(y, x) ~ 0 + Ly + Lx, data = lagged)
stats
Zero-intercept bivariate VAR
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Specify identical lag matrices and deterministic terms.
Stata reference · R reference
var y x, lags(1)
vargranger
lmtest::grangertest(y ~ x, order = 1, data = data)
lmtest
Test whether x Granger-predicts y
Differs from Stata: Fit var y x, lags(1) before vargranger; Stata VAR otherwise defaults to lags(1 2). grangertest uses an F reference distribution, whereas vargranger reports a Wald chi-square; match direction and sample, and do not interpret predictability as structural causation.
Stata reference · R reference
var y x, lags(1)
vargranger
lmtest::grangertest(x ~ y, order = 1, data = data)
lmtest
Test whether y Granger-predicts x
Differs from Stata: Fit var y x, lags(1) before vargranger; Stata VAR otherwise defaults to lags(1 2). grangertest uses an F reference distribution, whereas vargranger reports a Wald chi-square; match direction and sample, and do not interpret predictability as structural causation.
Stata reference · R reference
varstable
eigen(A, only.values = TRUE)$values
base
Eigenvalues of the VAR(1) companion matrix
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stability requires all companion roots strictly inside the unit circle.
Stata reference · R reference
vec y x, rank(1) lags(2)
urca::cajorls(urca::ca.jo(Y, type = "trace", ecdet = "none", K = 2, spec = "transitory"), r = 1)
urca
Rank-one vector error-correction model
Differs from Stata: urca ecdet="const" matches Stata trend(rconstant); ecdet="none" includes an unrestricted intercept and matches trend(constant); ecdet="trend" matches trend(rtrend). ca.jo does not provide Stata trend(none) or trend(trend). Match cointegrating-vector normalization before comparing coefficients.
Stata reference · R reference
vecrank y x, lags(2) trend(constant)
urca::ca.jo(Y, type = "trace", ecdet = "none", K = 2, spec = "transitory")
urca
Test cointegration rank with an unrestricted intercept
Differs from Stata: urca ecdet="const" matches Stata trend(rconstant); ecdet="none" includes an unrestricted intercept and matches trend(constant); ecdet="trend" matches trend(rtrend). ca.jo does not provide Stata trend(none) or trend(trend). Match cointegrating-vector normalization before comparing coefficients.
Stata reference · R reference
vecrank y x, lags(2) trend(constant) max
urca::ca.jo(Y, type = "eigen", ecdet = "none", K = 2, spec = "transitory")
urca
Test cointegration rank with an unrestricted intercept
Differs from Stata: urca ecdet="const" matches Stata trend(rconstant); ecdet="none" includes an unrestricted intercept and matches trend(constant); ecdet="trend" matches trend(rtrend). ca.jo does not provide Stata trend(none) or trend(trend). Match cointegrating-vector normalization before comparing coefficients.
Stata reference · R reference
vecrank y x, lags(2) trend(rconstant)
urca::ca.jo(Y, type = "trace", ecdet = "const", K = 2, spec = "transitory")
urca
Johansen trace rank test with a restricted constant
Differs from Stata: urca ecdet="const" matches Stata trend(rconstant); ecdet="none" includes an unrestricted intercept and matches trend(constant); ecdet="trend" matches trend(rtrend). ca.jo does not provide Stata trend(none) or trend(trend). Match cointegrating-vector normalization before comparing coefficients.
Stata reference · R reference
vecrank y x, lags(2) trend(rconstant) max
urca::ca.jo(Y, type = "eigen", ecdet = "const", K = 2, spec = "transitory")
urca
Johansen maximum-eigenvalue rank test with a restricted constant
Differs from Stata: urca ecdet="const" matches Stata trend(rconstant); ecdet="none" includes an unrestricted intercept and matches trend(constant); ecdet="trend" matches trend(rtrend). ca.jo does not provide Stata trend(none) or trend(trend). Match cointegrating-vector normalization before comparing coefficients.
Stata reference · R reference
vecrank y x, lags(2) trend(rtrend)
urca::ca.jo(Y, type = "trace", ecdet = "trend", K = 2, spec = "transitory")
urca
Johansen trace rank test with a restricted trend
Differs from Stata: urca ecdet="const" matches Stata trend(rconstant); ecdet="none" includes an unrestricted intercept and matches trend(constant); ecdet="trend" matches trend(rtrend). ca.jo does not provide Stata trend(none) or trend(trend). Match cointegrating-vector normalization before comparing coefficients.
Stata reference · R reference
vecrank y x, lags(2) trend(rtrend) max
urca::ca.jo(Y, type = "eigen", ecdet = "trend", K = 2, spec = "transitory")
urca
Johansen maximum-eigenvalue rank test with a restricted trend
Differs from Stata: urca ecdet="const" matches Stata trend(rconstant); ecdet="none" includes an unrestricted intercept and matches trend(constant); ecdet="trend" matches trend(rtrend). ca.jo does not provide Stata trend(none) or trend(trend). Match cointegrating-vector normalization before comparing coefficients.
Stata reference · R reference
predict e, residuals
wntestq e, lags(8)
stats::Box.test(stats::residuals(fit), lag = 8, type = "Ljung-Box", fitdf = 1)
stats
Ljung-Box test after AR(1) estimation
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R explicitly deducts the estimated AR parameter from the reference degrees of freedom.
Stata reference · R reference
wntestq y, lags(8)
stats::Box.test(y, lag = 8, type = "Ljung-Box")
stats
Ljung-Box serial-correlation portmanteau test
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Use fitdf for tests on estimated-model residuals.
Stata reference · R reference
xcorr y x, lags(8)
stats::ccf(y, x, lag.max = 8, plot = FALSE)
stats
Cross-correlation at positive and negative lags
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Check lag sign conventions before interpreting lead-lag direction.
Stata reference · R reference

Complex survey analysis

Stata R Purpose, qualifications and sources
estat cv
survey::cv(survey::svymean(~y, des))
survey
Coefficient of variation of a survey mean
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Relative standard error is unstable when the estimated mean is near zero.
Stata reference · R reference
estat effects
survey::deff(survey::svymean(~y, des, deff = TRUE))
survey
Design effect of a survey mean
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Design effects depend on the SRS comparison, finite-population correction and weight scaling.
Stata reference · R reference
svy bootstrap: mean y
{ reps <- survey::as.svrepdesign(des, type = "bootstrap"); survey::svymean(~y, reps) }
survey
Survey mean with bootstrap replicate variance
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Point means agree with sampling weights; replication variance depends on the chosen scheme.
Stata reference · R reference
svy brr: mean y
{ reps <- survey::as.svrepdesign(des, type = "BRR"); survey::svymean(~y, reps) }
survey
Survey mean with BRR replicate variance
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Point means agree with sampling weights; replication variance depends on the chosen scheme.
Stata reference · R reference
svy jackknife: mean y
{ reps <- survey::as.svrepdesign(des, type = "JKn"); survey::svymean(~y, reps) }
survey
Survey mean with JKn replicate variance
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Point means agree with sampling weights; replication variance depends on the chosen scheme.
Stata reference · R reference
svy, subpop(if group==1): mean y
survey::svymean(~y, subset(des, group == "1"))
survey
Survey subpopulation mean
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Subset the design, preserving the sampling structure, rather than rebuilding a design after filtering.
Stata reference · R reference
svy: glm y x, family(gamma) link(log)
survey::svyglm(y ~ x, des, family = stats::Gamma(link = "log"))
survey
Survey gamma log-link model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Quasi families retain the mean/variance structure without non-integer count warnings; align design degrees of freedom.
Stata reference · R reference
svy: logit yes x
survey::svyglm(yes ~ x, des, family = stats::quasibinomial())
survey
Survey logistic regression
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Quasi families retain the mean/variance structure without non-integer count warnings; align design degrees of freedom.
Stata reference · R reference
svy: mean y
survey::svymean(~y, des)
survey
Survey-weighted mean
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Design-based variance uses the full sampling design; population totals require correctly scaled weights.
Stata reference · R reference
svy: mean y x
survey::svymean(~y + x, des)
survey
Joint means and covariance matrix
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Design-based variance uses the full sampling design; population totals require correctly scaled weights.
Stata reference · R reference
svy: mean y, over(group)
survey::svyby(~y, ~group, des, survey::svymean)
survey
Domain-specific means
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Design-based variance uses the full sampling design; population totals require correctly scaled weights.
Stata reference · R reference
svy: poisson y x
survey::svyglm(y ~ x, des, family = stats::quasipoisson())
survey
Survey Poisson mean model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Quasi families retain the mean/variance structure without non-integer count warnings; align design degrees of freedom.
Stata reference · R reference
svy: probit yes x
survey::svyglm(yes ~ x, des, family = stats::quasibinomial(link = "probit"))
survey
Survey probit regression
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Quasi families retain the mean/variance structure without non-integer count warnings; align design degrees of freedom.
Stata reference · R reference
svy: proportion yes
survey::svymean(~factor(yes), des)
survey
Survey-weighted category proportions
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Design-based variance uses the full sampling design; population totals require correctly scaled weights.
Stata reference · R reference
svy: proportion yes
survey::svyciprop(~yes, des, method = "logit", level = .95)
survey
Survey proportion interval using logit
Fixed workflow; adapt the named data columns explicitly. Different interval constructions are intentional alternatives; match Stata's selected transformation.
Stata reference · R reference
svy: proportion yes
survey::svyciprop(~yes, des, method = "likelihood", level = .95)
survey
Survey proportion interval using likelihood
Fixed workflow; adapt the named data columns explicitly. Different interval constructions are intentional alternatives; match Stata's selected transformation.
Stata reference · R reference
svy: proportion yes
survey::svyciprop(~yes, des, method = "asin", level = .95)
survey
Survey proportion interval using asin
Fixed workflow; adapt the named data columns explicitly. Different interval constructions are intentional alternatives; match Stata's selected transformation.
Stata reference · R reference
svy: proportion yes
survey::svyciprop(~yes, des, method = "beta", level = .95)
survey
Survey proportion interval using beta
Fixed workflow; adapt the named data columns explicitly. Different interval constructions are intentional alternatives; match Stata's selected transformation.
Stata reference · R reference
svy: proportion yes
survey::svyciprop(~yes, des, method = "mean", level = .95)
survey
Survey proportion interval using mean
Fixed workflow; adapt the named data columns explicitly. Different interval constructions are intentional alternatives; match Stata's selected transformation.
Stata reference · R reference
svy: proportion yes
survey::svyciprop(~yes, des, method = "xlogit", level = .95)
survey
Survey proportion interval using xlogit
Fixed workflow; adapt the named data columns explicitly. Different interval constructions are intentional alternatives; match Stata's selected transformation.
Stata reference · R reference
svy: proportion yes, over(group)
survey::svyby(~factor(yes), ~group, des, survey::svymean)
survey
Domain-specific proportions
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Design-based variance uses the full sampling design; population totals require correctly scaled weights.
Stata reference · R reference
svy: ratio y/x
survey::svyratio(~y, ~x, des)
survey
Survey ratio of totals
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Design-based variance uses the full sampling design; population totals require correctly scaled weights.
Stata reference · R reference
svy: regress y x
survey::svyglm(y ~ x, des, family = stats::gaussian())
survey
Survey linear regression
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Quasi families retain the mean/variance structure without non-integer count warnings; align design degrees of freedom.
Stata reference · R reference
svy: tabulate group yes
prop.table(survey::svytable(~group + yes, des))
survey
Weighted contingency-table counts
Differs from Stata: Returns weighted cell proportions, the default display of svy: tabulate twoway. This table alone does not provide Stata design-based standard errors, confidence intervals or adjusted association tests.
Stata reference · R reference
svy: tabulate group yes, column
prop.table(survey::svytable(~group + yes, des), margin = 2)
survey
Survey column proportions
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Design-based variance uses the full sampling design; population totals require correctly scaled weights.
Stata reference · R reference
svy: tabulate group yes, pearson
survey::svychisq(~group + yes, des, statistic = "F")
survey
Design-based categorical association: F
Fixed workflow; adapt the named data columns explicitly. Rao-Scott and Wald choices have distinct reference distributions; choose the intended test explicitly.
Stata reference · R reference
svy: tabulate group yes, pearson
survey::svychisq(~group + yes, des, statistic = "Chisq")
survey
Design-based categorical association: Chisq
Fixed workflow; adapt the named data columns explicitly. Rao-Scott and Wald choices have distinct reference distributions; choose the intended test explicitly.
Stata reference · R reference
svy: tabulate group yes, pearson
survey::svychisq(~group + yes, des, statistic = "Wald")
survey
Design-based categorical association: Wald
Fixed workflow; adapt the named data columns explicitly. Rao-Scott and Wald choices have distinct reference distributions; choose the intended test explicitly.
Stata reference · R reference
svy: tabulate group yes, pearson
survey::svychisq(~group + yes, des, statistic = "adjWald")
survey
Design-based categorical association: adjWald
Fixed workflow; adapt the named data columns explicitly. Rao-Scott and Wald choices have distinct reference distributions; choose the intended test explicitly.
Stata reference · R reference
svy: tabulate group yes, row
prop.table(survey::svytable(~group + yes, des), margin = 1)
survey
Survey row proportions
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Design-based variance uses the full sampling design; population totals require correctly scaled weights.
Stata reference · R reference
svy: total y
survey::svytotal(~y, des)
survey
Survey-weighted population total
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Design-based variance uses the full sampling design; population totals require correctly scaled weights.
Stata reference · R reference
svy: total y x
survey::svytotal(~y + x, des)
survey
Joint population totals
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Design-based variance uses the full sampling design; population totals require correctly scaled weights.
Stata reference · R reference
svy: total y, over(group)
survey::svyby(~y, ~group, des, survey::svytotal)
survey
Domain-specific population totals
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Design-based variance uses the full sampling design; population totals require correctly scaled weights.
Stata reference · R reference
svydescribe
list(degrees_of_freedom = survey::degf(des), strata = table(des$strata[, 1]), clusters = length(unique(des$cluster[, 1])))
survey
Survey design degrees of freedom and cluster counts
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Counts observed records by stratum; PSU count is distinct from observation count.
Stata reference · R reference
svyset [pw=w]
survey::svydesign(ids = ~1, weights = ~w, data = data)
survey
Independent unequal-probability sample
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Survey objects carry design metadata; do not substitute ordinary regression weights.
Stata reference · R reference
svyset psu [pw=w], strata(stratum)
survey::svydesign(ids = ~psu, strata = ~stratum, weights = ~w, data = data)
survey
Stratified cluster survey design
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Survey objects carry design metadata; do not substitute ordinary regression weights.
Stata reference · R reference
svyset psu [pw=w], strata(stratum) fpc(N)
survey::svydesign(ids = ~psu, strata = ~stratum, weights = ~w, fpc = ~N, data = data)
survey
Finite-population correction in a clustered design
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Survey objects carry design metadata; do not substitute ordinary regression weights.
Stata reference · R reference
svyset psu [pw=w], strata(stratum) poststrata(group) postweight(pop)
survey::postStratify(des, ~group, population = population)
survey
Poststratify survey weights to population category totals
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Population categories must cover the sample; weighting adjustments are part of the variance design.
Stata reference · R reference
svyset psu [pw=w], strata(stratum) rake(ibn.group, totals(20 30, copy) noconstant)
survey::rake(des, sample.margins = list(~group), population.margins = list(population))
survey
Rake sample weights to known category margins
Fixed workflow; adapt the named data columns explicitly. Survey calibration workflow; Stata's exact calibration syntax depends on svyset options/version.
Stata reference · R reference
svyset psu [pw=w], strata(stratum) vce(bootstrap)
survey::as.svrepdesign(des, type = "bootstrap", replicates = 50)
survey
Survey bootstrap replicate-weight design
Fixed workflow; adapt the named data columns explicitly. Illustrative replication count; specific survey bootstrap schemes and scales can differ.
Stata reference · R reference
svyset psu [pw=w], strata(stratum) vce(brr)
survey::as.svrepdesign(des, type = "BRR")
survey
Balanced repeated replication for paired-PSU strata
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. BRR requires exactly two PSUs per stratum unless a deliberate design adjustment is made.
Stata reference · R reference
svyset psu [pw=w], strata(stratum) vce(brr) fay(.3)
survey::as.svrepdesign(des, type = "Fay", fay.rho = .3)
survey
Fay balanced repeated replication
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Match Fay's perturbation parameter and replicate scaling conventions.
Stata reference · R reference
svyset psu [pw=w], vce(jackknife)
survey::as.svrepdesign(des, type = "JKn")
survey
Stratified delete-one jackknife replicates
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Survey objects carry design metadata; do not substitute ordinary regression weights.
Stata reference · R reference

Meta-analysis

Stata R Purpose, qualifications and sources
meta bias, begg
metafor::ranktest(metafor::rma(yi, vi, data = data, method = "FE"))
metafor
Rank-correlation small-study-effects test
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Rank-correlation and small-sample p-value conventions may differ.
Stata reference · R reference
meta bias, egger
metafor::regtest(metafor::rma(yi, vi, data = data, method = "REML"), model = "rma", predictor = "sei")
metafor
Egger regression asymmetry test
Differs from Stata: Assumes the Stata meta declaration is its default random(reml). model="rma" regresses the effects on their standard errors with additive REML heterogeneity; model="lm" would instead use multiplicative dispersion. Small-study effects alone do not establish publication bias.
Stata reference · R reference
meta esize a b c d, esize(lnoratio)
metafor::escalc(measure = "OR", ai = a, bi = b, ci = c, di = d, data = data)
metafor
Log odds ratios and variances
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Use treatment/control cell ordering consistently and select continuity corrections deliberately.
Stata reference · R reference
meta esize a b c d, esize(lnrratio)
metafor::escalc(measure = "RR", ai = a, bi = b, ci = c, di = d, data = data)
metafor
Log risk ratios and variances
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Use treatment/control cell ordering consistently and select continuity corrections deliberately.
Stata reference · R reference
meta esize a b c d, esize(rdiff)
metafor::escalc(measure = "RD", ai = a, bi = b, ci = c, di = d, data = data)
metafor
Risk differences and variances
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Use treatment/control cell ordering consistently and select continuity corrections deliberately.
Stata reference · R reference
meta esize cases n, esize(ftukeyprop)
metafor::escalc(measure = "PFT", xi = cases, ni = n, data = data)
metafor
Freeman-Tukey transformed proportions
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Transformation definitions and back-transformation choices, especially double-arcsine, require care.
Stata reference · R reference
meta esize cases n, esize(logitprop)
metafor::escalc(measure = "PLO", xi = cases, ni = n, data = data)
metafor
Logit-transformed study proportions
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Transformation definitions and back-transformation choices, especially double-arcsine, require care.
Stata reference · R reference
meta esize cases n, esize(proportion)
metafor::escalc(measure = "PR", xi = cases, ni = n, data = data)
metafor
Raw study proportions and variances
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Transformation definitions and back-transformation choices, especially double-arcsine, require care.
Stata reference · R reference
meta esize n1 m1 sd1 n0 m0 sd0, esize(cohend)
metafor::escalc(measure = "SMD", m1i = m1, sd1i = sd1, n1i = n1, m2i = m0, sd2i = sd0, n2i = n0, data = data, correct = FALSE)
metafor
Uncorrected Cohen standardized mean differences
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Sampling-variance estimators for standardized effects must be matched.
Stata reference · R reference
meta esize n1 m1 sd1 n0 m0 sd0, esize(hedgesg)
metafor::escalc(measure = "SMD", m1i = m1, sd1i = sd1, n1i = n1, m2i = m0, sd2i = sd0, n2i = n0, data = data)
metafor
Bias-corrected standardized mean differences
Differs from Stata: metafor SMD uses the exact gamma-function Hedges correction. Stata hedgesg uses its approximation by default; specify esize(hedgesg, exact) to align that correction, and also match the sampling-variance formula.
Stata reference · R reference
meta esize n1 m1 sd1 n0 m0 sd0, esize(mdiff)
metafor::escalc(measure = "MD", m1i = m1, sd1i = sd1, n1i = n1, m2i = m0, sd2i = sd0, n2i = n0, data = data, vtype = "HO")
metafor
Unstandardized mean differences
Differs from Stata: vtype="HO" uses the pooled within-group variance, matching Stata esize(mdiff) default equal-variance sampling variance. metafor default vtype="LS" instead uses separate group variances; use it with Stata unequal.
Stata reference · R reference
meta esize r n, correlation
metafor::escalc(measure = "COR", ri = r, ni = n, data = data)
metafor
Raw correlations and sampling variances
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Correlations must be within (-1,1); sampling variance depends on transformation.
Stata reference · R reference
meta esize r n, fisherz
metafor::escalc(measure = "ZCOR", ri = r, ni = n, data = data)
metafor
Fisher-z transformed correlations
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Correlations must be within (-1,1); sampling variance depends on transformation.
Stata reference · R reference
meta regress c.year
metafor::rma(yi = yi, vi = vi, mods = ~year, data = data, method = "REML")
metafor
Meta-regression on centered publication year
Differs from Stata: Uses year on its original scale, so the intercept refers to year zero as in the Stata command. Assumes the Stata declared model is random(REML); match its model declaration and standard-error options.
Stata reference · R reference
meta regress i.x, random(reml)
metafor::rma(yi, vi, mods = ~factor(x), data = data, method = "REML")
metafor
Categorical meta-regression with Knapp-Hartung inference
Differs from Stata: Uses ordinary normal-reference REML meta-regression, as shown by the Stata command without se(khartung). Knapp-Hartung would require an explicit option in both systems. Moderator associations are study-level, not causal subgroup effects.
Stata reference · R reference
meta regress x
metafor::rma(yi = yi, vi = vi, mods = ~x, data = data, method = "REML")
metafor
Random-effects meta-regression with moderator
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Meta-regression relates study-level summaries, not individual-level effects.
Stata reference · R reference
meta set yi sei
metafor::escalc(measure = "GEN", yi = yi, sei = sei, data = data)
metafor
Declare generic effect sizes and sampling variances
Differs from Stata: Both examples take standard errors as sei; metafor stores their squares as vi. escalc creates effect-size data but does not persist a Stata-style meta declaration, labels or a default analysis model.
Stata reference · R reference
meta summarize, cumulative(year)
metafor::cumul(metafor::rma(yi, vi, data = data, method = "REML"), order = data$year)
metafor
Cumulative fixed-effect meta-analysis by year
Differs from Stata: Assumes meta set used its default random(reml) declaration; metafor explicitly selects REML. A prior Stata common/fixed/random declaration changes the target. Match study order, missingness and heterogeneity estimation before comparing summaries.
Stata reference · R reference
meta summarize, eform
exp(c(estimate = as.numeric(fit$b), lower = fit$ci.lb, upper = fit$ci.ub))
metafor
Exponentiate a pooled log-effect and interval
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Only appropriate when effects are on a log-ratio scale.
Stata reference · R reference
meta summarize, fixed
metafor::rma(yi = yi, vi = vi, data = data, method = "FE")
metafor
Inverse-variance meta-analysis using FE
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Between-study variance estimators and confidence procedures must be matched; some R estimator names differ from Stata's names.
Stata reference · R reference
meta summarize, leaveoneout
metafor::leave1out(metafor::rma(yi, vi, data = data, method = "REML"))
metafor
Leave-one-study-out pooled estimates
Differs from Stata: Assumes meta set used its default random(reml) declaration; metafor explicitly selects REML. A prior Stata common/fixed/random declaration changes the target. Match study order, missingness and heterogeneity estimation before comparing summaries.
Stata reference · R reference
meta summarize, random(dlaird)
metafor::rma(yi = yi, vi = vi, data = data, method = "DL")
metafor
Inverse-variance meta-analysis using DL
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Between-study variance estimators and confidence procedures must be matched; some R estimator names differ from Stata's names.
Stata reference · R reference
meta summarize, random(ebayes)
metafor::rma(yi = yi, vi = vi, data = data, method = "EB")
metafor
Inverse-variance meta-analysis using EB
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Between-study variance estimators and confidence procedures must be matched; some R estimator names differ from Stata's names.
Stata reference · R reference
meta summarize, random(hedges)
metafor::rma(yi = yi, vi = vi, data = data, method = "HE")
metafor
Inverse-variance meta-analysis using HE
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Between-study variance estimators and confidence procedures must be matched; some R estimator names differ from Stata's names.
Stata reference · R reference
meta summarize, random(mle)
metafor::rma(yi = yi, vi = vi, data = data, method = "ML")
metafor
Inverse-variance meta-analysis using ML
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Between-study variance estimators and confidence procedures must be matched; some R estimator names differ from Stata's names.
Stata reference · R reference
meta summarize, random(reml)
metafor::rma(yi = yi, vi = vi, data = data, method = "REML")
metafor
Inverse-variance meta-analysis using REML
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Between-study variance estimators and confidence procedures must be matched; some R estimator names differ from Stata's names.
Stata reference · R reference
meta summarize, random(reml)
metafor::rma(yi = yi, vi = vi, data = data, method = "REML", test = "z")
metafor
Random-effects pooled inference using z
Fixed workflow; adapt the named data columns explicitly. Only knha corresponds to a Knapp-Hartung correction; z/t are explicit inference alternatives.
Stata reference · R reference
meta summarize, random(reml) predinterval
stats::predict(metafor::rma(yi, vi, data = data, method = "REML"))
metafor
Prediction interval for a new study's true effect
Differs from Stata: The true-effect prediction interval differs from the pooled-mean confidence interval. Stata uses t(K-2); metafor defaults to a normal quantile. For Stata endpoints compute mu +/- qt(.975,K-2)*sqrt(tau2+se^2); changing metafor test="t" uses K-p degrees of freedom and is not the same correction.
Stata reference · R reference
meta summarize, random(reml) se(khartung)
metafor::rma(yi = yi, vi = vi, data = data, method = "REML", test = "knha")
metafor
Random-effects pooled inference using knha
Fixed workflow; adapt the named data columns explicitly. Only knha corresponds to a Knapp-Hartung correction; z/t are explicit inference alternatives.
Stata reference · R reference
meta summarize, random(reml) tdistribution
metafor::rma(yi = yi, vi = vi, data = data, method = "REML", test = "t")
metafor
Random-effects pooled inference using t
Fixed workflow; adapt the named data columns explicitly. Only knha corresponds to a Knapp-Hartung correction; z/t are explicit inference alternatives.
Stata reference · R reference
meta summarize, random(sjonkman)
metafor::rma(yi = yi, vi = vi, data = data, method = "SJ")
metafor
Inverse-variance meta-analysis using SJ
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Between-study variance estimators and confidence procedures must be matched; some R estimator names differ from Stata's names.
Stata reference · R reference
meta summarize, subgroup(x)
lapply(split(data, data$x), function(d) metafor::rma(yi, vi, data = d, method = "REML"))
metafor
Separate random-effects estimates by study subgroup
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Fits separate heterogeneity parameters; not the same as a shared-tau subgroup model.
Stata reference · R reference
meta trimfill
metafor::trimfill(metafor::rma(yi, vi, data = data, method = "REML"))
metafor
Trim-and-fill sensitivity analysis
Differs from Stata: Assumes meta set used its default random(reml) declaration; metafor explicitly selects REML. A prior Stata common/fixed/random declaration changes the target. Match study order, missingness and heterogeneity estimation before comparing summaries.
Stata reference · R reference

Multiple imputation

Stata R Purpose, qualifications and sources
mi convert flong
mice::complete(imp, action = "long", include = TRUE)
mice
Stack imputations including original data
Fixed workflow; adapt the named data columns explicitly. R mids metadata and storage structures differ from Stata MI data styles.
Stata reference · R reference
mi describe
list(imputations = imp$m, missing_by_variable = imp$nmis, methods = imp$method)
mice
Describe multiple-imputation metadata
Fixed workflow; adapt the named data columns explicitly. R mids metadata and storage structures differ from Stata MI data styles.
Stata reference · R reference
mi estimate, level(90): regress y x z
summary(mice::pool(with(imp, stats::lm(y ~ x + z))), conf.int = TRUE, conf.level = .90)
mice
Pooled estimates with ninety-percent intervals
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Uses mice's pooled small-sample degrees-of-freedom rules.
Stata reference · R reference
mi estimate: logit binary x z
mice::pool(with(imp, stats::glm(binary ~ x + z, family = stats::binomial())))
mice
Pool logistic-regression coefficients
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Pool on the log-odds scale before exponentiating.
Stata reference · R reference
mi estimate: mean x
{ completed <- mice::complete(imp, "all"); Q <- vapply(completed, function(d) mean(d$x), numeric(1)); U <- vapply(completed, function(d) stats::var(d$x) / nrow(d), numeric(1)); mice::pool.scalar(Q, U, n = nrow(data), k = 1) }
mice
Rubin pooling of an imputed continuous mean
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Within-imputation mean variances and complete-data sample sizes are explicit.
Stata reference · R reference
mi estimate: poisson count x z
mice::pool(with(imp, stats::glm(count ~ x + z, family = stats::poisson())))
mice
Pool Poisson-regression coefficients
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Pool log-rate coefficients; assess overdispersion separately.
Stata reference · R reference
mi estimate: regress y x z
mice::pool(with(imp, stats::lm(y ~ x + z)))
mice
Rubin pooling of linear-regression coefficients
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Pools within- and between-imputation variance; complete-data degrees of freedom must be appropriate.
Stata reference · R reference
mi estimate: regress y x z
{ fits <- lapply(mice::complete(imp, "all"), function(d) stats::lm(y ~ x + z, data = d)); mitools::MIcombine(lapply(fits, stats::coef), lapply(fits, stats::vcov)) }
mitools
Pool coefficient vectors and covariance matrices directly
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Alternative low-level Rubin pooling; degrees-of-freedom assumptions should be specified for small samples.
Stata reference · R reference
mi extract 1
mice::complete(imp, 1)
mice
Extract first completed dataset
Fixed workflow; adapt the named data columns explicitly. R mids metadata and storage structures differ from Stata MI data styles.
Stata reference · R reference
mi impute chained (logit) category (pmm, knn(5)) x z = y, add(3)
mice::mice(data, m = 3, maxit = 3, method = methods, seed = 131, donors = 5L, printFlag = FALSE)
mice
Binary logistic chained-equation imputation
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Set categorical types before imputation and match the model family; random draws are not cross-software identical.
Stata reference · R reference
mi impute chained (mlogit) category (pmm, knn(5)) x z = y, add(3)
mice::mice(data, m = 3, maxit = 3, method = methods, seed = 131, donors = 5L, printFlag = FALSE)
mice
Unordered-category chained-equation imputation
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Set categorical types before imputation and match the model family; random draws are not cross-software identical.
Stata reference · R reference
mi impute chained (ologit) category (pmm, knn(5)) x z = y, add(3)
mice::mice(data, m = 3, maxit = 3, method = methods, seed = 131, donors = 5L, printFlag = FALSE)
mice
Ordered-category chained-equation imputation
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Set categorical types before imputation and match the model family; random draws are not cross-software identical.
Stata reference · R reference
mi impute chained (pmm, knn(5)) x z = y, add(3) // restrict predictors
{ predictors <- mice::make.predictorMatrix(data); predictors["x", "z"] <- 0; mice::mice(data, m = 3, maxit = 3, predictorMatrix = predictors, seed = 132, donors = 5L, printFlag = FALSE) }
mice
Customize the imputation predictor matrix
Fixed workflow; adapt the named data columns explicitly. A workflow for per-variable models; the R predictor matrix is not inferred automatically from Stata syntax.
Stata reference · R reference
mi impute chained (pmm, knn(5)) x z = y, add(3) rseed(108)
mice::mice(data, m = 3, maxit = 3, method = "pmm", seed = 108, donors = 5L, printFlag = FALSE)
mice
Chained-equation imputation using pmm
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Imputation algorithms and random draws differ; specify predictor matrix and model types deliberately.
Stata reference · R reference
mi impute chained (regress) x z = y, add(3) rseed(108)
mice::mice(data, m = 3, maxit = 3, method = "norm", seed = 108, printFlag = FALSE)
mice
Chained-equation imputation using norm
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Imputation algorithms and random draws differ; specify predictor matrix and model types deliberately.
Stata reference · R reference
mi passive: generate square = x^2
lapply(mice::complete(imp, action = "all"), function(d) transform(d, square = x^2))
mice
Derive a nonlinear variable consistently in each completed dataset
Fixed workflow; adapt the named data columns explicitly. Post-imputation derivation is appropriate when the transform is not needed as an imputation predictor; otherwise use passive imputation within the chain.
Stata reference · R reference
mi test x
{ full <- with(imp, stats::lm(y ~ x + z)); reduced <- with(imp, stats::lm(y ~ z)); mice::D1(full, reduced) }
mice
Combine repeated complete-data Wald tests
D1 pools coefficient estimates and covariance matrices for a multivariate MI Wald test, as Stata mi test does. Use the same coefficient ordering and complete-data degrees of freedom; D2 pools test statistics and is a different rule.
Stata reference · R reference
mi test x z
{ full <- with(imp, stats::lm(y ~ x + z)); reduced <- with(imp, stats::lm(y ~ 1)); mice::D1(full, reduced) }
mice
Pooled multivariate Wald comparison
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. D1 combines nested-model Wald information; coefficients must have consistent ordering.
Stata reference · R reference
mi varying
vapply(imp$imp, function(z) if (nrow(z)) any(apply(z, 1, function(v) length(unique(v)) > 1)) else FALSE, logical(1))
mice
Identify variables varying across imputations
Fixed workflow; adapt the named data columns explicitly. R mids metadata and storage structures differ from Stata MI data styles.
Stata reference · R reference
mi xeq: summarize x
lapply(mice::complete(imp, action = "all"), function(d) summary(d$x))
mice
Inspect imputed-variable distributions in each dataset
Fixed workflow; adapt the named data columns explicitly. R mids metadata and storage structures differ from Stata MI data styles.
Stata reference · R reference

Multilevel models

Stata R Purpose, qualifications and sources
estat icc
{ v <- lme4::VarCorr(fit); between <- as.numeric(v$id[1, 1]); between / (between + stats::sigma(fit)^2) }
lme4
Random-intercept intraclass correlation
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. ICC is constant only for a random-intercept Gaussian model; random slopes make it covariate-dependent.
Stata reference · R reference
estat recovariance
as.matrix(lme4::VarCorr(fit)$id)
lme4
Random-effects covariance matrix
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Estimated covariance conditional on the chosen random-effects structure.
Stata reference · R reference
estat sd
as.data.frame(lme4::VarCorr(fit))
lme4
Variance components as standard deviations and correlations
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Includes residual standard deviation and random-effect correlation.
Stata reference · R reference
mecloglog binary x || id:, intpoints(1)
lme4::glmer(binary ~ x + (1 | id), data = data, family = stats::binomial(link = "cloglog"), nAGQ = 1, control = lme4::glmerControl(optimizer = "bobyqa"))
lme4
Complementary-log-log random-intercept model with Laplace approximation
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stata's integration settings must be matched; one Laplace point differs from adaptive quadrature.
Stata reference · R reference
mecloglog binary x || id:, intpoints(9)
lme4::glmer(binary ~ x + (1 | id), data = data, family = stats::binomial(link = "cloglog"), nAGQ = 9, control = lme4::glmerControl(optimizer = "bobyqa"))
lme4
Complementary-log-log random-intercept model with adaptive quadrature
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stata's integration settings must be matched; one Laplace point differs from adaptive quadrature.
Stata reference · R reference
meglm binary x || id:, family(binomial) link(cloglog)
lme4::glmer(binary ~ x + (1 | id), data = data, family = stats::binomial(link = "cloglog"), nAGQ = 7)
lme4
Generalized mixed model with cloglog link
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Explicit family/link choice; defaults and integration accuracy differ.
Stata reference · R reference
meglm binary x || id:, family(binomial) link(logit)
lme4::glmer(binary ~ x + (1 | id), data = data, family = stats::binomial(link = "logit"), nAGQ = 7)
lme4
Generalized mixed model with logit link
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Explicit family/link choice; defaults and integration accuracy differ.
Stata reference · R reference
meglm binary x || id:, family(binomial) link(probit)
lme4::glmer(binary ~ x + (1 | id), data = data, family = stats::binomial(link = "probit"), nAGQ = 7)
lme4
Generalized mixed model with probit link
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Explicit family/link choice; defaults and integration accuracy differ.
Stata reference · R reference
melogit binary x || id:, intpoints(1)
lme4::glmer(binary ~ x + (1 | id), data = data, family = stats::binomial(link = "logit"), nAGQ = 1, control = lme4::glmerControl(optimizer = "bobyqa"))
lme4
Logistic random-intercept model with Laplace approximation
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stata's integration settings must be matched; one Laplace point differs from adaptive quadrature.
Stata reference · R reference
melogit binary x || id:, intpoints(9)
lme4::glmer(binary ~ x + (1 | id), data = data, family = stats::binomial(link = "logit"), nAGQ = 9, control = lme4::glmerControl(optimizer = "bobyqa"))
lme4
Logistic random-intercept model with adaptive quadrature
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stata's integration settings must be matched; one Laplace point differs from adaptive quadrature.
Stata reference · R reference
menbreg nb x || id:
glmmTMB::glmmTMB(nb ~ x + (1 | id), data = data, family = glmmTMB::nbinom2())
glmmTMB
Negative-binomial mixed model with quadratic mean variance
Differs from Stata: glmmTMB uses Laplace integration; Stata menbreg defaults to intpoints(7) adaptive quadrature and needs intpoints(1) for a comparable integration approximation. Match NB2 dispersion versus its inverse before comparing ancillary parameters; identical integration does not itself guarantee estimator parity.
Stata reference · R reference
menl y = {A}*exp({B}*x), define(A: {a0}+{U[id]})
nlme::nlme(y ~ A * exp(B * x), data = data, fixed = A + B ~ 1, random = A ~ 1 | id, start = c(A = 2, B = .25))
nlme
Nonlinear exponential growth with random asymptote coefficient
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Nonlinear mixed-model workflow; Stata menl syntax/parameter definitions must match the desired model.
Stata reference · R reference
meologit ordinal x || id:
ordinal::clmm(ordinal ~ x + (1 | id), data = data, link = "logit", nAGQ = 7)
ordinal
Random-intercept cumulative-logit model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Threshold signs and quadrature defaults must be aligned.
Stata reference · R reference
meoprobit ordinal x || id:
ordinal::clmm(ordinal ~ x + (1 | id), data = data, link = "probit", nAGQ = 7)
ordinal
Random-intercept cumulative-probit model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Latent residual variance is fixed by the probit link.
Stata reference · R reference
mepoisson count x || id:, intpoints(1)
lme4::glmer(count ~ x + (1 | id), data = data, family = stats::poisson(link = "log"), nAGQ = 1, control = lme4::glmerControl(optimizer = "bobyqa"))
lme4
Poisson random-intercept model with Laplace approximation
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stata's integration settings must be matched; one Laplace point differs from adaptive quadrature.
Stata reference · R reference
mepoisson count x || id:, intpoints(9)
lme4::glmer(count ~ x + (1 | id), data = data, family = stats::poisson(link = "log"), nAGQ = 9, control = lme4::glmerControl(optimizer = "bobyqa"))
lme4
Poisson random-intercept model with adaptive quadrature
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stata's integration settings must be matched; one Laplace point differs from adaptive quadrature.
Stata reference · R reference
meprobit binary x || id:, intpoints(1)
lme4::glmer(binary ~ x + (1 | id), data = data, family = stats::binomial(link = "probit"), nAGQ = 1, control = lme4::glmerControl(optimizer = "bobyqa"))
lme4
Probit random-intercept model with Laplace approximation
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stata's integration settings must be matched; one Laplace point differs from adaptive quadrature.
Stata reference · R reference
meprobit binary x || id:, intpoints(9)
lme4::glmer(binary ~ x + (1 | id), data = data, family = stats::binomial(link = "probit"), nAGQ = 9, control = lme4::glmerControl(optimizer = "bobyqa"))
lme4
Probit random-intercept model with adaptive quadrature
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stata's integration settings must be matched; one Laplace point differs from adaptive quadrature.
Stata reference · R reference
mixed y c.x##c.x || id:
lme4::lmer(y ~ x + I(x^2) + (1 | id), data = data, REML = FALSE)
lme4
Quadratic fixed trend with random intercept
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R default REML differs from Stata mixed default ML; explicitly select the target likelihood.
Stata reference · R reference
mixed y x || id:
lme4::lmer(y ~ x + (1 | id), data = data, REML = FALSE)
lme4
REML random-intercept model
Differs from Stata: REML=FALSE explicitly matches Stata mixed default ML. lme4 does not print Stata large-sample fixed-effect z tests by default; match covariance structures and request the intended inference separately.
Stata reference · R reference
mixed y x || id: x, covariance(independent)
lme4::lmer(y ~ x + (x || id), data = data, REML = FALSE)
lme4
Independent random intercept and slope
Differs from Stata: REML=FALSE explicitly matches Stata mixed default ML. lme4 does not print Stata large-sample fixed-effect z tests by default; match covariance structures and request the intended inference separately.
Stata reference · R reference
mixed y x || id: x, covariance(unstructured)
lme4::lmer(y ~ x + (x | id), data = data, REML = FALSE)
lme4
Correlated random intercept and slope
Differs from Stata: REML=FALSE explicitly matches Stata mixed default ML. lme4 does not print Stata large-sample fixed-effect z tests by default; match covariance structures and request the intended inference separately.
Stata reference · R reference
mixed y x || id:, mle
lme4::lmer(y ~ x + (1 | id), data = data, REML = FALSE)
lme4
ML random-intercept model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R default REML differs from Stata mixed default ML; explicitly select the target likelihood.
Stata reference · R reference
predict fitted, fitted
stats::predict(fit)
lme4
Conditional fitted values including random effects
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Prediction level is explicit; population and cluster-specific predictions have different interpretations.
Stata reference · R reference
predict residual, residuals
stats::residuals(fit)
lme4
Conditional mixed-model residuals
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Prediction level is explicit; population and cluster-specific predictions have different interpretations.
Stata reference · R reference
predict u0 u1, reffects
lme4::ranef(fit)$id
lme4
Empirical Bayes random intercepts and slopes
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Prediction level is explicit; population and cluster-specific predictions have different interpretations.
Stata reference · R reference
predict xb, xb
stats::predict(fit, re.form = NA)
lme4
Fixed-effects-only predictions
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Prediction level is explicit; population and cluster-specific predictions have different interpretations.
Stata reference · R reference
quadchk
{ fits <- lapply(c(5, 9, 15), function(q) lme4::glmer(binary ~ x + (1 | id), data = data, family = stats::binomial(), nAGQ = q)); data.frame(points = c(5, 9, 15), logLik = vapply(fits, function(f) as.numeric(stats::logLik(f)), numeric(1)), slope = vapply(fits, function(f) unname(lme4::fixef(f)[2]), numeric(1))) }
lme4
Sensitivity of mixed-logit estimates to quadrature points
Fixed workflow; adapt the named data columns explicitly. Manual quadrature sensitivity check; not an automatic convergence guarantee.
Stata reference · R reference
xtologit ordinal x
ordinal::clmm(ordinal ~ x + (1 | id), data = data, link = "logit", nAGQ = 12)
ordinal
Random-intercept cumulative-logit model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Threshold signs and quadrature defaults must be aligned.
Stata reference · R reference
xtoprobit ordinal x
ordinal::clmm(ordinal ~ x + (1 | id), data = data, link = "probit", nAGQ = 12)
ordinal
Random-intercept cumulative-probit model
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Latent residual variance is fixed by the probit link.
Stata reference · R reference

Epidemiology

Stata R Purpose, qualifications and sources
cc case exposed
unname(a * d / (b * c))
base
Case-control cross-product odds ratio
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Odds ratio is identified under case-control sampling; absolute disease risk is not.
Stata reference · R reference
cc case exposed, exact
stats::fisher.test(tab, alternative = "two.sided")
stats
Exact conditional odds-ratio inference
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Conditional estimate and two-sided p-value conventions can differ.
Stata reference · R reference
cc case exposed, woolf
{ log_or <- log(a * d / (b * c)); se <- sqrt(sum(1 / tab)); exp(c(estimate = log_or, lower = log_or - qnorm(.975) * se, upper = log_or + qnorm(.975) * se)) }
stats
Approximate log-odds Wald interval
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Requires nonzero counts; no automatic continuity correction is applied.
Stata reference · R reference
cci 20 10 80 90
unname(a * d / (b * c))
base
Case-control cross-product odds ratio
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Odds ratio is identified under case-control sampling; absolute disease risk is not.
Stata reference · R reference
cci 20 10 80 90, exact
stats::fisher.test(tab, alternative = "two.sided")
stats
Exact conditional odds-ratio inference
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Conditional estimate and two-sided p-value conventions can differ.
Stata reference · R reference
cci 20 10 80 90, woolf
{ log_or <- log(a * d / (b * c)); se <- sqrt(sum(1 / tab)); exp(c(estimate = log_or, lower = log_or - qnorm(.975) * se, upper = log_or + qnorm(.975) * se)) }
stats
Approximate log-odds Wald interval
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Requires nonzero counts; no automatic continuity correction is applied.
Stata reference · R reference
cs case exposed
{ risk1 <- a / (a + c); risk0 <- b / (b + d); c(risk_exposed = risk1, risk_unexposed = risk0, risk_ratio = risk1 / risk0, risk_difference = risk1 - risk0) }
base
Risk ratio and risk difference
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Point measures assume a cohort with comparable follow-up; case-control sampling does not identify risk.
Stata reference · R reference
cs case exposed
{ rr <- (a / (a + c)) / (b / (b + d)); af_exposed <- 1 - 1 / rr; risk_population <- (a + b) / (a + b + c + d); c(attributable_fraction_exposed = af_exposed, attributable_fraction_population = (risk_population - b / (b + d)) / risk_population) }
base
Exposed and population attributable fractions
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Causal interpretation additionally requires exchangeability and correct study sampling.
Stata reference · R reference
cs case exposed, exact
stats::fisher.test(tab)
stats
Fisher exact association test for cohort table
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R reports a conditional maximum-likelihood odds ratio; Stata also reports sample cross-product measures.
Stata reference · R reference
cs case exposed, or woolf
{ odds <- a * d / (b * c); se <- sqrt(1 / a + 1 / b + 1 / c + 1 / d); c(odds_ratio = odds, lower = exp(log(odds) - qnorm(.975) * se), upper = exp(log(odds) + qnorm(.975) * se)) }
stats
Woolf odds-ratio interval in cohort table
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Woolf approximation requires positive cell counts.
Stata reference · R reference
csi 20 10 80 90
{ risk1 <- a / (a + c); risk0 <- b / (b + d); c(risk_exposed = risk1, risk_unexposed = risk0, risk_ratio = risk1 / risk0, risk_difference = risk1 - risk0) }
base
Risk ratio and risk difference
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Point measures assume a cohort with comparable follow-up; case-control sampling does not identify risk.
Stata reference · R reference
csi 20 10 80 90
{ rr <- (a / (a + c)) / (b / (b + d)); af_exposed <- 1 - 1 / rr; risk_population <- (a + b) / (a + b + c + d); c(attributable_fraction_exposed = af_exposed, attributable_fraction_population = (risk_population - b / (b + d)) / risk_population) }
base
Exposed and population attributable fractions
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Causal interpretation additionally requires exchangeability and correct study sampling.
Stata reference · R reference
csi 20 10 80 90, exact
stats::fisher.test(tab)
stats
Fisher exact association test for cohort table
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. R reports a conditional maximum-likelihood odds ratio; Stata also reports sample cross-product measures.
Stata reference · R reference
csi 20 10 80 90, or woolf
{ odds <- a * d / (b * c); se <- sqrt(1 / a + 1 / b + 1 / c + 1 / d); c(odds_ratio = odds, lower = exp(log(odds) - qnorm(.975) * se), upper = exp(log(odds) + qnorm(.975) * se)) }
stats
Woolf odds-ratio interval in cohort table
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Woolf approximation requires positive cell counts.
Stata reference · R reference
dstdize deaths population age, by(group) base(1)
sum(data$deaths / data$population * standard / sum(standard))
base
Direct standardization of stratum-specific rates
Fixed workflow; adapt the named data columns explicitly. Fixed one-population calculation; standard weights must represent the intended reference population.
Stata reference · R reference
ir cases exposed time
c(rate_exposed = 20 / 100, rate_unexposed = 10 / 200, incidence_rate_ratio = (20 / 100) / (10 / 200), rate_difference = 20 / 100 - 10 / 200)
base
Incidence-rate ratio and rate difference
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Counts and person-time denominators, not risks.
Stata reference · R reference
ir cases exposed time, exact
stats::poisson.test(c(20, 10), T = c(100, 200))
stats
Exact comparison of two Poisson incidence rates
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stata ir/iri default mid-p differs; this example requests exact inference.
Stata reference · R reference
iri 20 10 100 200
c(rate_exposed = 20 / 100, rate_unexposed = 10 / 200, incidence_rate_ratio = (20 / 100) / (10 / 200), rate_difference = 20 / 100 - 10 / 200)
base
Incidence-rate ratio and rate difference
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Counts and person-time denominators, not risks.
Stata reference · R reference
iri 20 10 100 200, exact
stats::poisson.test(c(20, 10), T = c(100, 200))
stats
Exact comparison of two Poisson incidence rates
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Stata ir/iri default mid-p differs; this example requests exact inference.
Stata reference · R reference
istdize deaths population age using reference, by(group)
{ expected <- sum(data$population * reference_rate); observed <- sum(data$deaths); c(observed = observed, expected = expected, SMR = observed / expected) }
base
Indirect standardization and mortality ratio
Fixed workflow; adapt the named data columns explicitly. Point estimates only; reference strata and person-time units must match.
Stata reference · R reference
mcc exposed_case exposed_control
stats::mcnemar.test(tab, correct = FALSE)
stats
McNemar comparison of matched binary exposures
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Uncorrected asymptotic statistic; exact or continuity-corrected alternatives differ.
Stata reference · R reference
mcc exposed_case exposed_control
c(matched_odds_ratio = tab[1, 2] / tab[2, 1], discordant_pairs = tab[1, 2] + tab[2, 1])
base
Matched odds ratio from discordant pairs
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Concordant pairs do not inform the matched odds ratio.
Stata reference · R reference
mcci 30 12 4 54
stats::mcnemar.test(tab, correct = FALSE)
stats
McNemar comparison of matched binary exposures
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Uncorrected asymptotic statistic; exact or continuity-corrected alternatives differ.
Stata reference · R reference
mcci 30 12 4 54
c(matched_odds_ratio = tab[1, 2] / tab[2, 1], discordant_pairs = tab[1, 2] + tab[2, 1])
base
Matched odds ratio from discordant pairs
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Concordant pairs do not inform the matched odds ratio.
Stata reference · R reference
mhodds case exposed stratum
stats::mantelhaen.test(tabs, correct = FALSE)
stats
Mantel-Haenszel common odds ratio
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Table orientation determines the odds-ratio direction; assumes a common stratum effect.
Stata reference · R reference
tabodds case exposed
{ out <- stats::aggregate(case ~ exposed, data = data, function(v) c(cases = sum(v), noncases = sum(1 - v))); data.frame(exposed = out$exposed, odds = out$case[, 1] / out$case[, 2]) }
stats
Odds of disease by exposure category
Fixed workflow; adapt the named data columns explicitly. Computes category odds only; no adjusted trend test.
Stata reference · R reference

Bayesian analysis

Stata R Purpose, qualifications and sources
bayesmh y x, likelihood(normal({var})) prior({y:}, normal(0,100)) prior({var}, igamma(1,1)) rseed(135)
MCMCpack::MCMCregress(y ~ x, data = data, burnin = 100, mcmc = 1000, b0 = 0, B0 = .01, c0 = 2, d0 = 2, seed = 135, verbose = 0)
MCMCpack
Bayesian Gaussian regression with normal and inverse-gamma priors
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Simple normal-regression model only; samplers and initialization differ. Short chains demonstrate syntax, not convergence.
Stata reference · R reference
bayespredict pmean, mean
drop(cbind(1, data$x) %*% colMeans(as.matrix(draws)[, c("(Intercept)", "x")]))
MCMCpack
Posterior mean Gaussian regression response
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Conditional mean prediction; observation noise is integrated to zero.
Stata reference · R reference
bayesreps yrep*, nreps(10)
{ set.seed(136); keep <- seq(1, nrow(draws), length.out = 10); B <- as.matrix(draws)[keep, ]; means <- cbind(1, data$x) %*% t(B[, c("(Intercept)", "x")]); means + matrix(rnorm(length(means), sd = rep(sqrt(B[, "sigma2"]), each = nrow(data))), nrow(data)) }
MCMCpack
Replicated outcomes from a Gaussian posterior predictive distribution
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Includes posterior parameter uncertainty and observation noise; no prediction files are written.
Stata reference · R reference
bayesstats ess
coda::effectiveSize(draws)
coda
Effective MCMC sample size
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Spectral-density ESS estimator differs from some Stata autocorrelation/batch calculations.
Stata reference · R reference
bayesstats summary
summary(draws)
coda
Posterior means, standard deviations and quantiles
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Summarizes supplied posterior draws; Monte Carlo errors differ by estimator.
Stata reference · R reference
bayesstats summary (effect:exp({y:x}))
summary(exp(draws[, "x", drop = FALSE]))
coda
Posterior summary of a transformed coefficient
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Transform draws before summarizing; exp(E[b]) differs from E[exp(b)].
Stata reference · R reference
bayesstats summary {y:x}, hpd clevel(90)
coda::HPDinterval(draws[, "x", drop = FALSE], prob = .9)
coda
Ninety-percent highest-posterior-density interval
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. HPD algorithms and multimodality handling can differ.
Stata reference · R reference
bayestest interval {y:x}, lower(0)
mean(draws[, "x"] > 0)
base
Posterior probability of a positive slope
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Monte Carlo probability of an interval hypothesis; not a frequentist p-value.
Stata reference · R reference
bayestest interval {y:x}, lower(1.8) upper(2.2)
mean(draws[, "x"] > 1.8 & draws[, "x"] < 2.2)
base
Posterior probability within a substantive effect interval
Differs from Stata: Fixed workflow; adapt the named data columns explicitly. Choose the substantive interval before inspecting posterior results.
Stata reference · R reference

R functions by package

R Package Stata Description
ivreg() AER ivregress Instrumental-Variable Regression
tobit() AER Tobit (censored) regression
dbAppendTable() DBI jdbc Insert rows into a table
dbDisconnect() DBI odbc Disconnect (close) a connection
dbGetQuery() DBI odbc Retrieve results from a query
dbListFields() DBI odbc List field names of a remote table
dbListTables() DBI odbc List remote tables
dbReadTable() DBI jdbc Read database tables as data frames
oblimin() GPArotation rotate Rotations Functions Using Gradient Projection Algorithms
quartimax() GPArotation rotate Rotations Functions Using Gradient Projection Algorithms
boxcox() MASS boxcox Box-Cox Transformations for Linear Models
corresp() MASS ca Simple Correspondence Analysis
glm.nb() MASS Negative binomial regression
isoMDS() MASS mds Kruskal's Non-metric Multidimensional Scaling
lda() MASS discrim Linear Discriminant Analysis
mca() MASS mca Multiple Correspondence Analysis
mvrnorm() MASS drawnorm Simulate from a Multivariate Normal Distribution
polr() MASS Ordered logit or probit
qda() MASS discrim Quadratic Discriminant Analysis
rlm() MASS Robust regression
MCMCregress() MCMCpack bayesmh Markov Chain Monte Carlo for Gaussian Linear Regression
match_data() MatchIt psmatch2 Construct a matched dataset from a matchit object
matchit() MatchIt Matching for causal inference
synth() Synth Synthetic control
SurvS4() VGAM cpoisson Create a Survival Object
binom2.rho() VGAM biprobit Bivariate Probit Regression
cens.poisson() VGAM cpoisson Censored Poisson Family Function
multinomial() VGAM slogit Multinomial Logit Model
posnegbinomial() VGAM tnbreg Positive Negative Binomial Distribution Family Function
posnormal() VGAM truncreg Positive Normal Distribution Family Function
pospoisson() VGAM tpoisson Positive Poisson Distribution Family Function
rrvglm() VGAM slogit Fitting Reduced-Rank Vector Generalized Linear Models (RR-VGLMs) and Doubly Constrained RR-VGLMs (DRR-VGLMs)
vglm() VGAM tpoisson Fitting Vector Generalized Linear Models
weightit() WeightIt Balancing weights, such as inverse-probability weights
.libPaths() base adopath Search Paths for Packages
I() base regress Inhibit Interpretation/Conversion of Objects
Mod() base psdensity Complex Numbers and Basic Functionality
R.home() base sysdir Return the R Home Directory
Sys.Date() base Today's date
Sys.sleep() base sleep Suspend Execution for a Time Interval
Sys.time() base c(current_time) Current date and time
abs() base abs() Absolute value
all() base assert Whether all values are TRUE
any() base count if Whether any value is TRUE
anyDuplicated() base gisid Determine Duplicate Elements
anyNA() base gisid Not Available / Missing Values
apply() base egen rowtotal() Apply a function over rows or columns
as.Date() base Convert to a date
as.POSIXct() base clock Date-time Conversion Functions
as.character() base Convert to text
as.data.frame() base getmata Coerce to a Data Frame
as.double() base Convert to double-precision numbers
as.factor() base encode Convert to a factor
as.integer() base Convert to whole numbers
as.matrix() base cf Matrices
as.numeric() base Convert to numbers
as.vector() base margins Vectors - Creation, Coercion, etc
attr() base Get or set an attribute of an object
attributes() base char Object Attribute Lists
body() base viewsource Access to and Manipulation of the Body of a Function
c() base Combine values into a vector
cat() base Print text without quotes
cbind() base merge 1:1 _n Put side by side (base R)
ceiling() base Round up
charToRaw() base changeeol Convert to or from (Bit/Packed) Raw Vectors
character() base tokenize Character Vectors
chol() base irf The Cholesky Decomposition
class() base describe Class of an object
close() base file Functions to Manipulate Connections (Files, URLs, ...)
col() base spmatrix Column Indexes
colMeans() base margins Form Row and Column Sums and Means
colSums() base missings Form Row and Column Sums and Means
colnames() base ds Column names
crossprod() base tsfilter Matrix Cross-Product
cumprod() base generate Running product
cumsum() base Running sum
cut() base Cut numbers into intervals
data.frame() base range Data Frames
diag() base Diagonal of a matrix
diff() base D. Differences between neighbouring values
dim() base describe Numbers of rows and columns
dir() base List files in a folder
dir.create() base mkdir Create a folder
do.call() base program Call a function with a list of arguments
double() base postfile Double-Precision Vectors
dput() base dataex Write an Object to a File or Recreate it
drop() base lincom Drop Redundant Extent Information
droplevels() base label define Drop unused factor levels
duplicated() base gegen Determine Duplicate Elements
eigen() base varstable Spectral Decomposition of a Matrix
environment() base include Environment Access
exp() base exp() Exponential
expand.grid() base arimasoc Create a Data Frame from All Combinations of Factor Variables
factor() base Categorical variable with labelled levels
file() base file Functions to Manipulate Connections (Files, URLs, ...)
file.copy() base copy File Manipulation
file.exists() base confirm file Whether a file exists
file.info() base hexdump Extract File Information
file.path() base global path Build a file path
floor() base Round down
format() base Format values for display
formatC() base string(x, "%9.2f") Format numbers with width and padding
getwd() base Show the working directory
grep() base unab Pattern Matching and Replacement
grepl() base Whether text matches a pattern
gsub() base subinstr() Replace every match
iconv() base unicode Convert Character Vector between Encodings
identical() base cf Test Objects for Exact Equality
ifelse() base cond() Vectorised if-else (base R)
integer() base gdistinct Integer Vectors
interaction() base egen group() Combine factors into one
invisible() base exit Change the Print Mode to Invisible
is.character() base confirm string variable Whether a vector holds text
is.infinite() base gencohort Finite, Infinite and NaN Numbers
is.na() base Whether values are missing
is.nan() base egen Finite, Infinite and NaN Numbers
is.numeric() base confirm numeric variable Whether a vector holds numbers
lapply() base foreach Apply a function to each element, returning a list
length() base count Number of elements
lengths() base wordcount Lengths of List or Vector Elements
levels() base Categories of a factor
library() base ssc install Attach a package
list() base A list of objects
list.files() base dir Files in a folder
load() base use Load objects from an .RData file
local() base tempvar Evaluate an (Unevaluated) Expression
log() base Logarithm (natural by default)
log10() base log10() Base-10 logarithm
logical() base missings Logical Vectors
ls() base List objects in memory
make.names() base Turn text into valid names
mapply() base arimasoc Apply a Function to Multiple List or Vector Arguments
match() base rename Value Matching
match.arg() base unabcmd Argument Verification Using Partial Matching
matrix() base Create a matrix
max() base Largest value
mean() base Mean
merge() base merge Merge two data frames (base R)
message() base display Print a message
min() base Smallest value
names() base Names of an object, such as column names
nchar() base strlen() Number of characters
ncol() base describe Number of columns
nlevels() base levelsof Number of factor levels
normalizePath() base findfile Express File Paths in Canonical Form
nrow() base Number of rows
numeric() base rangestat Numeric Vectors
options() base set Set global options
order() base sort Positions that would sort a vector
paste() base Join text with a separator
paste0() base Join text without a separator
plot() base Basic plot
pmatch() base unab Partial String Matching
pmax() base max(a, b) Element-wise maximum of several vectors
pmin() base min(a, b) Element-wise minimum of several vectors
print() base Print an object
prop.table() base Turn counts into proportions
proportions() base tabulate, row Turn a table into proportions
qr() base orthog The QR Decomposition of a Matrix
qr.Q() base orthog Reconstruct the Q, R, or X Matrices from a QR Object
range() base summarize Minimum and maximum
rank() base Ranks, with ties averaged
rbind() base append Stack rows (base R)
readBin() base hexdump Transfer Binary Data To and From Connections
readLines() base changeeol Read Text Lines from a Connection
readRDS() base use Read an R object file (.rds)
regexpr() base strpos Pattern Matching and Replacement
rep() base expand Repeat values
rep_len() base Repeat values to a given length
replace() base generate Replace Values in a Vector
replicate() base bootstrap Apply a Function over a List or Vector
requireNamespace() base ftools Loading and Unloading Name Spaces
return() base exit Function Definition
rev() base gsort Reverse the order
rm() base Remove objects from memory
round() base Round to a number of decimals
row() base spmatrix Row Indexes
rowMeans() base egen Form Row and Column Sums and Means
rowSums() base Sum across columns in each row
sample() base sample Random sample of values
sample.int() base bsample Random Samples and Permutations
sapply() base foreach Apply a function to each element and simplify
save() base save Save objects to an .RData file
saveRDS() base Save one R object to a file
scale() base egen std() Standardise columns
scan() base tokenize Read Data Values
seq() base Sequence of numbers
seq_along() base _n Positions of the elements of a vector
seq_len() base _n Whole numbers from 1 to n
serialize() base datasignature Simple Serialization Interface
set.seed() base Make random numbers reproducible
setwd() base Change the working directory
sign() base compare Sign Function
signif() base round() Round to significant digits
sin() base tsfilter Trigonometric Functions
sink() base Send console output to a file
solve() base estat Solve a System of Equations
sort() base Sort a vector
source() base Run an R script
split() base by Split data into groups
sprintf() base Format numbers and text with a template
sqrt() base Square root
stop() base exit 198 Stop with an error
stopifnot() base Stop if a condition is not TRUE
strsplit() base split Split strings
sub() base regexr() Replace the first match
subset() base keep if Rows meeting a condition (base R)
substr() base substr() Part of a string by position
sum() base Sum
summary() base Summary of an object, such as a model
sys.source() base include Parse and Evaluate Expressions from a File
t() base Transpose a matrix
table() base Count values
tapply() base bysort g: egen Apply a function within groups
tempdir() base sysdir Create Names for Temporary Files
tempfile() base Name for a temporary file
tolower() base strlower() Lower case
toupper() base strupper() Upper case
traceback() base Show where the last error happened
transform() base expandcl Transform an Object, for Example a Data Frame
trimws() base strtrim() Remove leading and trailing spaces
trunc() base int() Drop the decimals
try() base capture Run code and continue after an error
tryCatch() base capture Handle errors and warnings
typeof() base describe Storage type
unclass() base rotate Object Classes
unique() base Distinct values
unname() base cf Remove names or dimnames
unsplit() base permute Divide into Groups and Reassemble
vapply() base gdistinct Apply a Function over a List or Vector
vector() base irf Vectors - Creation, Coercion, etc
warning() base display as error Give a warning
which() base list if Positions where a condition is TRUE
with() base Evaluate code with the columns of a data frame
writeBin() base changeeol Transfer Binary Data To and From Connections
writeLines() base checksum Write Lines to a Connection
xor() base egen Logical Operators
betareg() betareg betareg Beta Regression for Rates and Proportions
binsreg() binsreg Binned scatter plot and estimation
boot() boot centile Bootstrap Resampling
boot.ci() boot centile Nonparametric Bootstrap Confidence Intervals
augment() broom predict Add fitted values and residuals to the data
glance() broom One-row summary of model statistics
tidy() broom Coefficient table as a data frame
Anova() car anova Type II and III ANOVA tables
avPlots() car Added-variable plots
deltaMethod() car nlcom Estimate and Standard Error of a Nonlinear Function of Estimated Regression Coefficients
leveneTest() car robvar Levene's Test
linearHypothesis() car test Test linear restrictions on coefficients
vif() car Variance inflation factors
knn() class discrim k-Nearest Neighbour Classification
bal.tab() cobalt pstest Display Balance Statistics in a Table
HPDinterval() coda bayesstats Highest Posterior Density intervals
effectiveSize() coda bayesstats Effective sample size for estimating the mean
fread() data.table import delimited Fast reading of large text files
fwrite() data.table export delimited Fast writing of large text files
winsorize() datawizard Winsorise extreme values
att_gt() did Staggered difference in differences (Callaway-Sant'Anna)
across() dplyr Apply the same calculation to several columns
add_count() dplyr bysort g: generate n = _N Add a column with group counts
all_of() dplyr keep `vars' Select columns named in a character vector
anti_join() dplyr Keep rows of the first table with no match in the second
any_of() dplyr capture keep Select listed columns that exist
arrange() dplyr Sort rows
between() dplyr Whether values lie within a range
bind_cols() dplyr Put tables side by side
bind_rows() dplyr Stack tables on top of each other
c_across() dplyr egen rowtotal() Combine columns inside rowwise()
case_match() dplyr recode Recode values by matching them
case_when() dplyr Several if-else conditions in one step
coalesce() dplyr First non-missing value across vectors
consecutive_id() dplyr tsspell Number runs of identical values
contains() dplyr Select columns whose names contain some text
count() dplyr Count rows in each group
cross_join() dplyr Every combination of rows from two tables
cumall() dplyr sum() Running all(): TRUE until the first FALSE
cume_dist() dplyr cumul Cumulative distribution
cur_group() dplyr by Keys of the current group
cur_group_id() dplyr Number of the current group
dense_rank() dplyr egen group() Ranks without gaps
desc() dplyr Sort in descending order inside arrange()
distinct() dplyr Keep unique rows
ends_with() dplyr Select columns whose names end with some text
everything() dplyr _all Select all columns
filter() dplyr Keep rows that meet a condition
first() dplyr x[1] First value
full_join() dplyr Merge keeping all rows of both tables
glimpse() dplyr describe Compact view of all columns
group_by() dplyr Group rows so later steps work within groups
group_split() dplyr by Split a table into one table per group
group_vars() dplyr by Names of the grouping variables
if_all() dplyr egen rowmin() Whether a condition holds in all of several columns
if_any() dplyr egen anymatch() Whether a condition holds in any of several columns
if_else() dplyr One value if a condition holds, another if not
inner_join() dplyr Merge keeping only matched rows
intersect() dplyr merge, keep(match) Rows in both tables
join_by() dplyr joinby Join keys, including inequality and range joins
lag() dplyr Value from the previous row
last() dplyr x[_N] Last value
last_col() dplyr order The last column
lead() dplyr Value from the next row
left_join() dplyr Merge keeping all rows of the first table
matches() dplyr Select columns whose names match a regular expression
min_rank() dplyr egen rank(), track Ranks with ties given the lowest rank
mutate() dplyr Create or change columns
n() dplyr Number of rows in the current group
n_distinct() dplyr distinct Number of distinct values
na_if() dplyr Turn one value into missing
near() dplyr reldif() Compare numbers with a tolerance
nth() dplyr x[5] Value at a given position
ntile() dplyr xtile Split into n groups of nearly equal size
num_range() dplyr keep x1-x5 Select x1, x2 and so on by number
percent_rank() dplyr egen rank() Rank rescaled to 0-1
pick() dplyr varlist Select columns inside mutate() or summarise()
pull() dplyr Extract one column as a vector
reframe() dplyr collapse Summarise to any number of rows per group
relocate() dplyr Move columns to a new position
rename() dplyr Rename columns (new = old)
rename_with() dplyr Rename columns with a function, such as toupper
right_join() dplyr Merge keeping all rows of the second table
row_number() dplyr Row number
rows_update() dplyr merge, update replace Update rows from another table
rowwise() dplyr egen rowmean() Compute row by row
select() dplyr Keep or drop columns
semi_join() dplyr Keep rows of the first table that have a match in the second
setdiff() dplyr merge, keep(master) Rows in the first table only
slice() dplyr Keep rows by position
slice_head() dplyr bysort g: keep if _n <= 3 First rows of each group
slice_max() dplyr gsort -x; keep in 1/5 Rows with the largest values
slice_min() dplyr sort x; keep in 1/5 Rows with the smallest values
slice_sample() dplyr Random sample of rows
slice_tail() dplyr bysort g: keep if _n > _N - 3 Last rows of each group
starts_with() dplyr Select columns whose names start with some text
summarise() dplyr Reduce each group to one row of statistics
summarize() dplyr collapse Same as summarise()
tally() dplyr count Count rows
transmute() dplyr keep Create columns and keep only those
ungroup() dplyr Remove grouping
union() dplyr append Rows in either table, without duplicates
where() dplyr ds, has(type numeric) Select columns by type, such as where(is.numeric)
cohens_d() effectsize esize Cohen's d and Other Standardized Differences
iv_robust() estimatr ivregress Two-Stage Least Squares Instrumental Variables Regression
coefplot() fixest coefplot Coefficient plot for fixest models
etable() fixest esttab Regression table for fixest models
feglm() fixest xtlogit GLM, such as logit, with fixed effects
fenegbin() fixest xtnbreg Negative binomial model with fixed effects
feols() fixest Linear regression with fixed effects, clustering and IV
fepois() fixest Poisson regression with fixed effects
fitstat() fixest estat firststage Fit statistics, including the first-stage F
sunab() fixest eventstudyinteract Sun and Abraham interactions
flextable() flextable Formatted table for Word or PowerPoint
save_as_docx() flextable Save tables to a Word file
fct_collapse() forcats recode Combine levels into groups
fct_count() forcats tabulate Count each level
fct_drop() forcats label define Drop unused levels
fct_infreq() forcats tabulate x, sort Order levels by frequency
fct_lump_n() forcats recode Lump rare levels into Other
fct_na_value_to_level() forcats tabulate x, missing Make missing values a level
fct_recode() forcats label define, modify Rename factor levels
fct_relevel() forcats ib3.x Move factor levels to the front
fct_reorder() forcats graph bar, sort Order levels by another variable
fct_rev() forcats label define Reverse the order of levels
Arima() forecast forecast Fit ARIMA model to univariate time series
forecast() forecast forecast Objects exported from other packages
fracdiff() fracdiff arfima ML Estimates for Fractionally-Differenced ARIMA (p,d,q) models
boottest() fwildclusterboot boottest Fast wild cluster bootstrap inference
geeglm() geepack xtgee Fit Generalized Estimating Equations (GEE)
aes() ggplot2 Map variables to x, y, colour and other plot features
after_stat() ggplot2 histogram Control aesthetic evaluation
annotate() ggplot2 text() Add one annotation, such as text
coord_cartesian() ggplot2 xscale(range()) Zoom in without dropping data
coord_flip() ggplot2 Swap the x and y axes
coord_polar() ggplot2 Polar coordinates, used for pie charts
facet_grid() ggplot2 by() Panels by two variables
facet_wrap() ggplot2 One panel per group
geom_abline() ggplot2 function Line with a given slope and intercept
geom_area() ggplot2 Area plot
geom_bar() ggplot2 Bar chart of counts
geom_boxplot() ggplot2 Box plot
geom_col() ggplot2 graph bar (asis) Bars with given heights
geom_contour() ggplot2 twoway 2D contours of a 3D surface
geom_density() ggplot2 Density curve
geom_errorbar() ggplot2 Error bars or capped ranges
geom_histogram() ggplot2 Histogram
geom_hline() ggplot2 yline() Horizontal reference line
geom_jitter() ggplot2 scatter, jitter() Jittered points
geom_label() ggplot2 mlabel() Text labels in boxes
geom_line() ggplot2 Lines connecting observations
geom_linerange() ggplot2 twoway Vertical intervals: lines, crossbars & errorbars
geom_point() ggplot2 Points (scatter plot)
geom_pointrange() ggplot2 rcap Points with intervals
geom_qq() ggplot2 Quantile-quantile points
geom_qq_line() ggplot2 Reference line for a quantile-quantile plot
geom_rect() ggplot2 twoway Rectangles
geom_ribbon() ggplot2 Shaded band between two values
geom_segment() ggplot2 twoway Line segments and curves
geom_sf() ggplot2 spmap Map from spatial data
geom_smooth() ggplot2 Fitted line or smooth curve
geom_step() ggplot2 line, connect(stairstep) Step plot
geom_text() ggplot2 Text labels on a plot
geom_tile() ggplot2 heatplot Heat-map tiles
geom_violin() ggplot2 Violin plot
geom_vline() ggplot2 Vertical reference line
ggplot() ggplot2 Start a plot
ggsave() ggplot2 Save a plot to a file
labs() ggplot2 title() Title and axis labels
position_dodge() ggplot2 over() Place bars or points side by side
position_jitter() ggplot2 dotplot Jitter points to avoid overplotting
scale_colour_manual() ggplot2 mcolor() Choose colours by hand
scale_fill_brewer() ggplot2 set scheme ColorBrewer fill colours
scale_x_continuous() ggplot2 xlabel() Axis breaks and labels
scale_x_log10() ggplot2 xscale(log) Logarithmic x axis
scale_y_continuous() ggplot2 scatter Position scales for continuous data (x & y)
scale_y_log10() ggplot2 scatter Position scales for continuous data (x & y)
stat_ecdf() ggplot2 cumul Empirical cumulative distribution plot
stat_summary() ggplot2 Plot a summary, such as the mean, of y at each x
stat_summary_2d() ggplot2 heatplot Summarize a variable within two-dimensional bins
theme() ggplot2 graphregion() Fine-tune the look of a plot
theme_bw() ggplot2 Black-and-white plot theme
theme_classic() ggplot2 set scheme Classic plot theme
theme_minimal() ggplot2 set scheme Minimal plot theme
theme_set() ggplot2 Set the default theme for every plot
xlim() ggplot2 xscale(range()) Limits of the x axis
glmmTMB() glmmTMB menbreg Fit Models with TMB
nbinom2() glmmTMB menbreg Family functions for glmmTMB
cv.glmnet() glmnet lasso Cross-validation for glmnet
pairs() graphics Scatter-plot matrix
plot() graphics quantile The Default Scatterplot Function
stem() graphics Stem-and-leaf display
arrow() grid twoway Describe arrows to add to a line
tbl_cross() gtsummary tabulate x1 x2 Cross table
tbl_regression() gtsummary esttab Regression table
tbl_summary() gtsummary Descriptive Table 1
as_factor() haven decode Turn labelled values into a factor
is_tagged_na() haven mvencode "Tagged" missing values
labelled() haven Attach value labels to a vector
print_labels() haven label list Show value labels
read_dta() haven Read a Stata .dta file
read_sas() haven Read a SAS file
read_sav() haven Read an SPSS .sav file
read_xpt() haven import Read and write SAS transport files
tagged_na() haven replace x = .a Stata-style extended missing values such as .a
write_dta() haven Write a Stata .dta file
write_sav() haven savespss Write an SPSS file
write_xpt() haven export Read and write SAS transport files
zap_labels() haven Remove value labels
zap_missing() haven mvdecode Turn special missing values into NA
adorn_totals() janitor tabulate x1 x2 Add totals to a tabyl
clean_names() janitor rename *, lower Clean and lower-case variable names
get_dupes() janitor duplicates list List duplicated rows
remove_empty() janitor missings dropvars Drop empty rows and columns
tabyl() janitor tabulate Frequency and cross tables
look_for() labelled lookfor Find variables by name or label
set_variable_labels() labelled Set variable labels
to_factor() labelled decode Turn labelled values into a factor
val_labels() labelled label values Get or set value labels
var_label() labelled label variable Get or set a variable label
cfa() lavaan sem Fit Confirmatory Factor Analysis Models
fitMeasures() lavaan estat Fit Measures for a Latent Variable Model
lavResiduals() lavaan estat Residuals
modindices() lavaan estat Modification Indices
sem() lavaan Structural equation model
standardizedSolution() lavaan sem Standardized Solution
VarCorr() lme4 estat sd Variance components of a multilevel model
fixef() lme4 quadchk Extract fixed-effects estimates
glmer() lme4 Multilevel generalised linear model
glmerControl() lme4 melogit Control of Mixed Model Fitting
lmer() lme4 Multilevel linear model
ranef() lme4 predict, reffects Predicted random effects
bptest() lmtest Breusch-Pagan test for heteroskedasticity
coeftest() lmtest Coefficient tests with a chosen variance matrix
grangertest() lmtest vargranger Test for Granger Causality
lrtest() lmtest Likelihood-ratio test
resettest() lmtest RESET test for omitted variables
waldtest() lmtest test Wald test of nested models
as_date() lubridate dofc() Convert to a date
day() lubridate Day of the month
days() lubridate d + 7 A period of days, for date arithmetic
days_in_month() lubridate daysinmonth Get the number of days in the month of a date-time
dmy() lubridate date(s, "DMY") Parse day-month-year text into a date
floor_date() lubridate mofd() Round a date down to a unit, such as the month
hour() lubridate hh() Hour of a date-time
interval() lubridate Time span between two dates
make_date() lubridate Date from year, month and day
make_datetime() lubridate mdyhms() Date-time from its parts
mdy() lubridate date(s, "MDY") Parse month-day-year text into a date
minute() lubridate mm() Minute of a date-time
month() lubridate Month of a date
now() lubridate now() Current date and time
quarter() lubridate quarter() Quarter of a date
time_length() lubridate Length of a time span in chosen units, such as years
today() lubridate today() Today's date
wday() lubridate Day of the week
week() lubridate week() Week of the year
yday() lubridate doy() Day of the year
year() lubridate Year of a date
years() lubridate d + 365 A period of years, for date arithmetic
ymd() lubridate Parse text such as 2024-01-31 into a date
ymd_hms() lubridate Parse text into a date-time
avg_comparisons() marginaleffects margins r.x Average contrasts
avg_predictions() marginaleffects Average predictions, like Stata's margins
avg_slopes() marginaleffects Average marginal effects
comparisons() marginaleffects margins r.x Differences between predictions (contrasts)
hypotheses() marginaleffects Tests of linear and nonlinear hypotheses
plot_predictions() marginaleffects Plot predictions, like marginsplot
plot_slopes() marginaleffects marginsplot Plot marginal effects
predictions() marginaleffects margins Predictions with standard errors
slopes() marginaleffects margins, dydx(x) at() Marginal effects for each observation
cumul() metafor meta Cumulative Meta-Analysis for 'rma' Objects
escalc() metafor meta Calculate Effect Sizes and Outcome Measures
leave1out() metafor meta Leave-One-Out Diagnostics for 'rma' Objects
ranktest() metafor meta Rank Correlation Test for Funnel Plot Asymmetry
regtest() metafor meta Regression Test for Funnel Plot Asymmetry
rma() metafor meta Meta-Analysis via Linear (Mixed-Effects) Models
trimfill() metafor meta Trim and Fill Analysis for 'rma.uni' Objects
D1() mice mi Compare two nested models using D1-statistic
D2() mice mi Compare two nested models using D2-statistic
complete() mice mi Extracts the completed data from a mids object
make.predictorMatrix() mice mi Creates a predictorMatrix argument
mice() mice Multiple imputation by chained equations
pool() mice Combine results across imputations
pool.scalar() mice mi Multiple imputation pooling: univariate version
MIcombine() mitools mi Multiple imputation inference
datasummary() modelsummary tabstat Custom summary-statistics tables
datasummary_skim() modelsummary codebook Quick overview of all variables
modelplot() modelsummary Coefficient plot
modelsummary() modelsummary Regression and summary tables
glht() multcomp contrast General Linear Hypotheses
mcp() multcomp contrast General Linear Hypotheses
dmvnorm() mvtnorm lnmvnormalden Multivariate Normal Density and Random Deviates
pmvnorm() mvtnorm binormal Multivariate Normal Distribution
corAR1() nlme xtregar AR(1) Correlation Structure
gls() nlme hetregress Fit Linear Model Using Generalized Least Squares
lme() nlme xtregar Linear Mixed-Effects Models
nlme() nlme menl Nonlinear Mixed-Effects Models
varExp() nlme hetregress Exponential Variance Function
varIdent() nlme xtgls Constant Variance Function
multinom() nnet Multinomial logit
oaxaca() oaxaca Blinder-Oaxaca decomposition
clmm() ordinal meologit Cumulative Link Mixed Models
coords() pROC roctab Coordinates of a ROC curve
roc() pROC roctab Build a ROC curve
roc.test() pROC roccomp Compare two ROC curves
wrap_plots() patchwork Combine several plots
pdata.frame() plm xtset Declare panel data for plm
pgmm() plm Dynamic panel GMM (Arellano-Bond)
phtest() plm hausman Hausman test
plm() plm Panel models: fixed and random effects
plmtest() plm xttest0 Lagrange FF Multiplier Tests for Panel Models
purtest() plm xtunitroot Unit root tests for panel data
vcovBK() plm xtpcse Beck and Katz Robust Covariance Matrix Estimators
vcovHC() plm xtreg Robust Covariance Matrix Estimators
vcovSCC() plm xtreg Driscoll and Kraay (1998) Robust Covariance Matrix Estimator
polychor() polycor tetrachoric Polychoric Correlation
zeroinfl() pscl zip Zero-inflated Count Data Regression
ICC() psych icc Intraclass Correlations (ICC1, ICC2, ICC3 from Shrout and Fleiss)
KMO() psych estat Find the Kaiser, Meyer, Olkin Measure of Sampling Adequacy
alpha() psych alpha Cronbach's alpha
cohen.kappa() psych kap Find Cohen's kappa and weighted kappa coefficients for correlation of two raters
describe() psych summarize Summary statistics (unlike Stata's describe)
fa() psych factor Factor analysis with more methods
mardia() psych mvtest Calculate univariate or multivariate (Mardia's test) skew and kurtosis for a vector, matrix, or data.frame
principal() psych factor Principal components analysis (PCA)
list_rbind() purrr append Stack a list of data frames
map() purrr foreach Apply a function to each element, returning a list
map2() purrr forvalues Apply a function to pairs of elements
map_chr() purrr foreach Apply a function to each element, returning text
map_dbl() purrr foreach Apply a function to each element, returning numbers
possibly() purrr capture Return a default value instead of an error
reduce() purrr merge Combine elements one after another, such as repeated merges
walk() purrr foreach Apply a function for its side effects, such as saving files
ES.h() pwr power Effect size calculation for proportions
pwr.anova.test() pwr power Power calculations for balanced one-way analysis of variance tests
pwr.f2.test() pwr power Power calculations for the general linear model
pwr.norm.test() pwr power Power calculations for the mean of a normal distribution (known variance)
pwr.p.test() pwr power Power calculations for proportion tests (one sample)
pwr.r.test() pwr power Power calculations for correlation test
pwr.t2n.test() pwr power Power calculations for two samples (different sizes) t-tests of means
rq() quantreg Quantile regression
rdbwdensity() rddensity rdbwdensity Bandwidth Selection for Manipulation Testing
rddensity() rddensity rddensity Manipulation Testing Using Local Polynomial Density Estimation
rdbwselect() rdrobust rdbwselect Bandwidth Selection Procedures for Local Polynomial Regression Discontinuity Estimators
rdrobust() rdrobust Regression discontinuity
parse_number() readr destring, ignore() Extract a number from text such as $1,200
read_csv() readr Read a CSV file
read_delim() readr import delimited Read a file with any delimiter
read_tsv() readr import delimited Read a tab-separated file
write_csv() readr Write a CSV file
excel_sheets() readxl import excel, describe Sheet names of an Excel file
read_excel() readxl Read an Excel sheet
install_github() remotes Install a package from GitHub
find_root() rprojroot setroot Find the root of a directory hierarchy
has_file() rprojroot setroot Is a directory the project root?
selection() sampleSelection Heckman sample-selection model
NeweyWest() sandwich newey Newey-West HAC Covariance Matrix Estimation
vcovBS() sandwich Bootstrap variance matrix
vcovCL() sandwich vce(cluster id) Clustered variance matrix
vcovHC() sandwich vce(robust) Heteroskedasticity-robust variance matrix
vcovJK() sandwich Jackknife variance matrix
st_as_sf() sf spset Convert foreign object to an sf object
as_survey_design() srvyr Declare a survey design
survey_mean() srvyr Survey-weighted mean
survey_prop() srvyr Survey-weighted proportion
survey_quantile() srvyr epctile Survey-weighted quantiles
survey_total() srvyr svy: total Survey-weighted total
AIC() stats Akaike information criterion
BIC() stats Bayesian information criterion
Box.test() stats wntestq #1BoxBox-#1PiercePierce and #1LjungLjung-#1BoxBox Tests
Gamma() stats glm Family Objects for Models
HoltWinters() stats tssmooth Holt-Winters Filtering
IQR() stats egen iqr() Interquartile range
StructTS() stats sspace Fit Structural Time Series
TukeyHSD() stats pwcompare, mcompare(tukey) Tukey multiple comparisons
acf() stats corrgram Autocorrelation function
addmargins() stats tabulate x1 x2 Add totals to a table
aggregate() stats collapse Group statistics (base R)
anova() stats anova ANOVA table, or comparison of nested models
aov() stats Analysis of variance
approx() stats ipolate Interpolation Functions
arima() stats ARIMA time-series model
as.dist() stats mdsmat Distance Matrix Computation
ave() stats stgen Group Averages Over Level Combinations of Factors
bartlett.test() stats oneway Bartlett test of equal variances
binom.test() stats bitest Exact binomial test
binomial() stats Binomial family for logit and probit models
cancor() stats canon Canonical Correlations
ccf() stats xcorr Auto- and Cross- Covariance and -Correlation Function Estimation
chisq.test() stats tabulate x1 x2, chi2 Chi-square test
cmdscale() stats mds Classical (Metric) Multidimensional Scaling
coef() stats Model coefficients
complete.cases() stats egen rowmiss() Rows with no missing values
confint() stats regress Confidence intervals of coefficients
cooks.distance() stats predict Regression Deletion Diagnostics
cor() stats Correlation matrix
cor.test() stats Correlation with a significance test
cov() stats correlate, covariance Covariance
cov2cor() stats estat Correlation, Variance and Covariance (Matrices)
cutree() stats cluster Cut a Tree into Groups of Data
dbeta() stats betaden The Beta Distribution
dbinom() stats binomialp The Binomial Distribution
dcauchy() stats cauchyden The Cauchy Distribution
dchisq() stats chi2den The (non-central) Chi-Squared Distribution
density() stats kdensity Kernel density estimate
dexp() stats exponentialden The Exponential Distribution
df() stats Fden The F Distribution
dfbetas() stats dfbeta Regression Deletion Diagnostics
dffits() stats predict Regression Deletion Diagnostics
dgamma() stats gammaden The Gamma Distribution
dhyper() stats hypergeometricp The Hypergeometric Distribution
dist() stats mds Distance Matrix Computation
dlogis() stats logisticden The Logistic Distribution
dnbinom() stats nbinomialp The Negative Binomial Distribution
dnorm() stats normalden() Normal density
dpois() stats poissonp The Poisson Distribution
dt() stats tden The Student t Distribution
dweibull() stats weibullden The Weibull Distribution
ecdf() stats cumul Empirical cumulative distribution
expand.model.frame() stats vce(cluster g) Retrieve additional variables aligned with a fitted model's observations
factanal() stats Factor analysis
filter() stats tssmooth Linear Filtering on a Time Series
fisher.test() stats Fisher's exact test
fitted() stats Fitted values of a model
ftable() stats table Flat multi-way table
gaussian() stats glm Family Objects for Models
glm() stats Generalised linear model, such as logit or Poisson
hatvalues() stats predict Regression Deletion Diagnostics
hclust() stats cluster Hierarchical Clustering
inverse.gaussian() stats glm Family Objects for Models
kmeans() stats K-means clustering
kruskal.test() stats Kruskal-Wallis test
ks.test() stats Kolmogorov-Smirnov test
lm() stats Linear regression
logLik() stats e(ll) Log-likelihood of a model
lowess() stats lowess Lowess smoother
mad() stats egen mad() Median absolute deviation
manova() stats manova Multivariate Analysis of Variance
mantelhaen.test() stats mhodds Cochran-Mantel-#1HaenszelHaenszel Chi-Squared Test for Count Data
mcnemar.test() stats mcc McNemar test for paired proportions
median() stats Median
model.frame() stats estat Extracting the Model Frame from a Formula or Fit
model.matrix() stats xi Design matrix with dummy variables
na.omit() stats Drop rows with missing values
nls() stats nl Nonlinear least squares
nobs() stats e(N) Number of observations used by a model
offset() stats poisson Include an Offset in a Model Formula
optim() stats ml General-purpose optimisation
p.adjust() stats test, mtest Adjust p-values for multiple tests
pacf() stats pac Auto- and Cross- Covariance and -Correlation Function Estimation
pairwise.t.test() stats pwmean Pairwise t tests with adjusted p-values
pbeta() stats ibeta The Beta Distribution
pbinom() stats binomial The Binomial Distribution
pcauchy() stats cauchy The Cauchy Distribution
pchisq() stats chi2tail() Chi-square probability
pexp() stats exponential The Exponential Distribution
pf() stats F The F Distribution
pgamma() stats gammap The Gamma Distribution
phyper() stats hypergeometric The Hypergeometric Distribution
plogis() stats predictnl The Logistic Distribution
pnbinom() stats nbinomial The Negative Binomial Distribution
pnorm() stats normal() Normal cumulative probability
poisson() stats glm Family Objects for Models
poisson.test() stats stir Exact Poisson tests
poly() stats Polynomial terms for a model
power.prop.test() stats power Power Calculations for Two-Sample Test for Proportions
power.t.test() stats power twomeans Power and sample size for a t test
ppoints() stats quantile Ordinates for Probability Plotting
ppois() stats poisson The Poisson Distribution
prcomp() stats Principal components
predict() stats Predictions from a model
princomp() stats pcamat Principal Components Analysis
promax() stats rotate Rotation Methods for Factor Analysis
prop.test() stats Test of a proportion
prop.trend.test() stats nptrend Test for trend in proportions
pt() stats ttail() t-distribution probability
ptukey() stats tukeyprob The Studentized Range Distribution
pweibull() stats weibull The Weibull Distribution
qbeta() stats invibeta The Beta Distribution
qcauchy() stats invcauchy The Cauchy Distribution
qchisq() stats qchi The (non-central) Chi-Squared Distribution
qexp() stats invexponential The Exponential Distribution
qf() stats invF The F Distribution
qgamma() stats invgammap The Gamma Distribution
qlogis() stats invlogistic The Logistic Distribution
qnorm() stats invnormal() Normal quantile
qqplot() stats qqplot Quantile-Quantile Plots
qt() stats invt The Student t Distribution
qtukey() stats invtukeyprob The Studentized Range Distribution
quantile() stats pctile Quantiles
quasibinomial() stats Binomial family that allows survey weights
quasipoisson() stats svy Family Objects for Models
qweibull() stats invweibull The Weibull Distribution
rbeta() stats rbeta The Beta Distribution
rbinom() stats rbinomial() Binomial random numbers
rcauchy() stats rcauchy The Cauchy Distribution
rchisq() stats rchi2 The (non-central) Chi-Squared Distribution
relevel() stats Choose the base category of a factor
reshape() stats icc Reshape Grouped Data
residuals() stats predict, residuals Model residuals
rexp() stats rexponential The Exponential Distribution
rgamma() stats rgamma The Gamma Distribution
rhyper() stats rhypergeometric The Hypergeometric Distribution
rlogis() stats rlogistic The Logistic Distribution
rnbinom() stats rnbinomial The Negative Binomial Distribution
rnorm() stats Normal random numbers
rpois() stats rpoisson The Poisson Distribution
rstandard() stats predict Regression Deletion Diagnostics
rstudent() stats predict Regression Deletion Diagnostics
rt() stats rt The Student t Distribution
runif() stats Uniform random numbers
runmed() stats tssmooth Running Medians -- Robust Scatter Plot Smoothing
rweibull() stats rweibull The Weibull Distribution
sd() stats Standard deviation
setNames() stats labmask Set the Names in an Object
shapiro.test() stats Shapiro-Wilk normality test
sigma() stats estat Extract Residual Standard Deviation 'Sigma'
spectrum() stats pergram Spectral Density Estimation
step() stats stepwise Stepwise model selection
t.test() stats t test and confidence interval of a mean
ts() stats tsset Time-series object
uniroot() stats ciwidth One Dimensional Root (Zero) Finding
update() stats regress Refit a model with changes
var() stats summarize, detail Variance
var.test() stats sdtest F test of equal variances
varimax() stats rotate Rotation Methods for Factor Analysis
vcov() stats Variance-covariance matrix of a model
weighted.mean() stats summarize [aweight = w] Weighted mean
wilcox.test() stats Wilcoxon rank-sum or signed-rank test
xtabs() stats tabulate x1 x2 Cross-tabulation from a formula
stri_reverse() stringi ustrreverse Reverse Each String
stri_trans_nfc() stringi ustrnormalize Perform or Check For Unicode Normalization
stri_trans_nfkc() stringi ustrnormalize Perform or Check For Unicode Normalization
fixed() stringr Match text literally rather than as a regular expression
regex() stringr Regular expression with options such as ignore_case
str_c() stringr generate s = a + b Join strings
str_count() stringr Count matches in a string
str_detect() stringr Whether a string contains a pattern
str_dup() stringr "-" * 10 Repeat a string
str_ends() stringr substr() Whether a string ends with a pattern
str_extract() stringr Extract the matching text
str_extract_all() stringr ustrregexs() Extract every match
str_flatten() stringr levelsof, separate() Collapse a vector into one string
str_glue() stringr display "`x'" Fill a text template
str_length() stringr Number of characters
str_locate() stringr strpos() Position of a match
str_match() stringr regexs() Extract the groups of a regular expression
str_pad() stringr string(x, "%05.0f") Pad a string to a fixed width
str_remove() stringr subinstr() Remove the first match
str_remove_all() stringr subinstr() Remove every match
str_replace() stringr Replace the first match
str_replace_all() stringr Replace every match
str_split() stringr split Split strings into pieces
str_squish() stringr Trim spaces and collapse repeated spaces
str_starts() stringr substr() Whether a string starts with a pattern
str_sub() stringr Part of a string by position
str_subset() stringr keep if regexm() Keep the strings that match
str_to_lower() stringr Lower case
str_to_sentence() stringr strproper() Sentence case
str_to_title() stringr Title case
str_to_upper() stringr Upper case
str_trim() stringr Remove leading and trailing spaces
str_trunc() stringr abbrev() Shorten strings to a width
str_wrap() stringr display Wrap text into lines
word() stringr Extract words from a sentence
as.svrepdesign() survey svyset Convert a survey design to use replicate weights
cv() survey estat Summary statistics for sample surveys
deff() survey estat Summary statistics for sample surveys
degf() survey svydescribe Contingency tables for survey data
postStratify() survey svyset Post-stratify a survey
rake() survey svyset Raking of replicate weight design
svyby() survey svy Survey statistics on subsets
svychisq() survey svy Contingency tables for survey data
svyciprop() survey svy Confidence intervals for proportions
svydesign() survey svyset Declare a survey design (survey package)
svyglm() survey Survey-weighted regression
svymean() survey svy: mean Survey-weighted mean (survey package)
svyratio() survey svy Ratio estimation
svytable() survey svy: tabulate Survey-weighted table
svytotal() survey svy Summary statistics for sample surveys
Surv() survival Survival-time outcome for a model
basehaz() survival predict Alias for the survfit function
clogit() survival Conditional logit
concordance() survival estat Compute the concordance statistic for data or a model
cox.zph() survival estat Test the Proportional Hazards Assumption of a Cox Regression
coxph() survival Cox proportional hazards model
finegray() survival stcrreg Create data for a Fine-Gray model
frailty() survival stcox Random effects terms
strata() survival Stratum term in a survival model formula
survSplit() survival stsplit Split a survival data set at specified times
survdiff() survival Log-rank test
survfit() survival Kaplan-Meier survival curves
survreg() survival Parametric survival model
add_row() tibble set obs Add rows to a table
as_tibble() tibble Convert to a tibble
rownames_to_column() tibble xpose Turn row names into a column
tibble() tibble Create a data frame (tibble)
tribble() tibble input Type a small table row by row
complete() tidyr Add rows for missing combinations of values
crossing() tidyr cross All combinations, sorted and unique
drop_na() tidyr drop if missing(x) Drop rows with missing values
expand() tidyr fillin All combinations of values, dropping other columns
expand_grid() tidyr cross Table of every combination of given values
fill() tidyr Fill missing values with the previous or next value
full_seq() tidyr tsfill Complete sequence of values
nest() tidyr by Nest rows into list-columns, one row per group
pivot_longer() tidyr Reshape from wide to long
pivot_wider() tidyr Reshape from long to wide
replace_na() tidyr replace x = 0 if missing(x) Replace missing values
separate_longer_delim() tidyr split Split text into rows
separate_wider_delim() tidyr Split one text column into several
separate_wider_position() tidyr substr() Split text into columns by position
uncount() tidyr Repeat each row a given number of times
unite() tidyr egen concat() Join columns into one
unnest() tidyr expand Expand list-columns back into rows
as_character() tidystata decode Alias of decode()
as_dummy() tidystata Dummy variables for every category
as_numeric() tidystata destring Alias of destring()
assert() tidystata Stop and count the rows where a condition fails
browse() tidystata View data in a spreadsheet window
capture() tidystata Return the result or report a caught error and return NULL; quiet suppresses warnings and messages
codebook() tidystata Describe every variable: type, label, counts and values
corr() tidystata Complete-case Pearson correlations
cut_quantile() tidystata xtile Alias of xtile()
decode() tidystata Convert to text, using value labels for labelled data
destring() tidystata Convert to numbers, dropping value labels
ds() tidystata List variable names
duplicates_drop() tidystata Drop duplicated rows, keeping the first
duplicates_list() tidystata List duplicated rows
duplicates_report() tidystata Count duplicated rows
duplicates_tag() tidystata Mark duplicated rows
findit() tidystata Find the R equivalent of a Stata command
fre() tidystata Frequency table with a total row
fre2() tidystata tabulate Two-way cross-tabulation with row and column totals
is_first() tidystata Mark the first row of each group
isid() tidystata Check that variables uniquely identify the rows
misstable() tidystata Missing values per variable, or missing-value patterns
mvdecode() tidystata Turn given codes into missing values
mvencode() tidystata Replace missing values with a code
na_if_value() tidystata mvdecode Alias of mvdecode()
pc() tidystata Percentage of the total
pct() tidystata egen pc() Alias of pc()
print_all() tidystata Print every row and column
pwcorr() tidystata Pairwise correlations with counts and p-values
row_max() tidystata Maximum across variables in each row
row_mean() tidystata Mean across variables in each row
row_median() tidystata Median across variables in each row
row_min() tidystata Minimum across variables in each row
row_miss() tidystata Number of missing values in each row
row_non_miss() tidystata Number of observed values in each row
row_nvals() tidystata Number of distinct values in each row, ignoring missing values
row_sd() tidystata Standard deviation across variables in each row
row_sum() tidystata Sum across variables in each row
row_unique() tidystata egen rownvals() Number of distinct values in each row, counting missing as one
set_seed() tidystata Set the random seed, alone or at the end of a pipe
stata_diff() tidystata Difference from the previous period, respecting time gaps
stata_lag() tidystata Value from an earlier period, respecting time gaps
stata_lead() tidystata Value from a later period, respecting time gaps
stata_merge() tidystata Merge two tables and report matches, like Stata's merge
std() tidystata Standardise to mean 0 and standard deviation 1
summ() tidystata Summary statistics for variables
tab() tidystata Frequency table
tab1() tidystata One frequency table per variable
tab2() tidystata Two-way cross-tabulation, or every pairwise table
tab_gen() tidystata tabulate, generate() Alias of as_dummy()
tabstat() tidystata Chosen statistics for variables, optionally by group
timer() tidystata Time how long code takes
tostring() tidystata Convert to text, keeping codes rather than value labels
value_if_na() tidystata mvencode Alias of mvencode()
variables() tidystata List variables with their types and labels
variables_search() tidystata Find variables by name or label
varlist() tidystata Select variables with Stata wildcards such as x*
xtile() tidystata Quantile groups, following Stata's xtile
md5sum() tools checksum Compute MD5 Checksums
garch() tseries arch Fit GARCH Models to Time Series
as_tsibble() tsibble Declare time-series or panel data
fill_gaps() tsibble Add rows for missing time points
yearmonth() tsibble Monthly period
yearquarter() tsibble Quarterly period
ca.jo() urca vecrank Johansen Procedure for VAR
cajorls() urca vec OLS regression of VECM
ur.df() urca dfuller Augmented-Dickey-Fuller Unit Root Test
ur.ers() urca dfgls Elliott, Rothenberg and Stock Unit Root Test
ur.pp() urca pperron Phillips and Perron Unit Root Test
View() utils browse Open the data viewer
capture.output() utils dataex Send Output to a Character String or File
combn() utils tab2 Generate All Combinations of n Elements, Taken m at a Time
data() utils Load a built-in example dataset
getAnywhere() utils Find where a function is defined
glob2rx() utils Turn a wildcard pattern into a regular expression
head() utils First rows
help() utils Open a help page
help.search() utils Search all installed help pages
install.packages() utils Install a package from CRAN
object.size() utils memory Report the Space Allocated for an Object
packageVersion() utils ftools Package Description
read.csv() utils import delimited Read a CSV file (base R)
read.delim() utils import Data Input
read.fwf() utils infix Read Fixed Width Format Files
read.table() utils infile Data Input
sessionInfo() utils about Collect Information About the Current R Session
str() utils Compact view of an object's structure
tail() utils Last rows
unzip() utils unzipfile Extract or List Zip Archives
update.packages() utils Update installed packages
write.csv() utils export delimited Write a CSV file (base R)
write.table() utils outfile Data Output
write_xlsx() writexl Write an Excel file
zipr() zip zipfile Compress Files into 'zip' Archives
na.locf() zoo stfill Last Observation Carried Forward
rollapply() zoo rolling Apply Rolling Functions