Programming utilities

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

about

Inspect R version and platform information

Stata

about

R Package:utils

utils::sessionInfo()

Reports R session metadata; Stata license and serial information have no R counterpart.

adopath

Inspect the package library search path

Stata

adopath

R Package:base

.libPaths()

R package libraries replace ado search directories; this only reads the current path.

args

Receive two positional arguments in a function

Stata

program define addtwo
args a b
display `a'+`b'
end

R Package:base

addtwo <- function(a,b) a+b

R function arguments replace positional Stata macros; this is a fixed program example.

continue

Skip the rest of one loop iteration

Stata

forvalues i=1/4 {
    if `i'==2 continue
    display `i'
}

R Package:base

out <- integer(); for (i in 1:4) { if(i==2) next; out <- c(out,i) }

Fixed workflow example; adapt the object and column names together.

Exit a loop early

Stata

forvalues i=1/4 {
    if `i'==3 continue, break
    display `i'
}

R Package:base

out <- integer(); for (i in 1:4) { if(i==3) break; out <- c(out,i) }

Fixed workflow example; adapt the object and column names together.

creturn

Inspect R version, platform, paths and numeric limits

Stata

creturn list

R Package:base

list(version=R.version.string,platform=R.version$platform,working_directory=getwd(),machine=.Machine)

Returns R’s own settings and constants, not Stata’s c-class values.

dataex

Create reproducible R code for a small data example

Stata

dataex id x in 1/3

R Package:base

example <- data[1:3,c('id','x')]; text <- utils::capture.output(dput(example))

dput emits R reconstruction code, not Stata input code or forum markup. Share only data already approved for disclosure.

error

Raise a clear error from a function

Stata

error 198

R Package:base

fail <- function() stop('Invalid input',call.=FALSE)

R conditions replace numeric Stata return codes; the check catches the deliberately raised error.

exit

Return early from a function

Stata

program define positive
args x
if `x'<=0 exit
display `x'
end

R Package:base

positive <- function(x) { if(x<=0) return(invisible(NULL)); x }

Function-level return only; quitting the R process would terminate the user’s session.

ftools

Inspect the R data-manipulation package version and availability

Stata

ftools, version

R Package:utils

list(version=as.character(utils::packageVersion('dplyr')),available=requireNamespace('dplyr',quietly=TRUE))

Reports the chosen R workflow dependency, dplyr; it does not inspect or compile a Stata Mata library.

gettoken

Split the first simple token from the remaining text

Stata

gettoken first rest : text

R Package:base

parts <- strsplit(text,' +')[[1]]; first <- parts[1]; rest <- paste(parts[-1],collapse=' ')

Differs from Stata Simple unquoted whitespace tokens only; Stata quoting and bind rules are not reproduced.

include

Execute helper code in the current evaluation environment

Stata

include helper.do

R Package:base

sys.source(path,envir=environment())

Only sources the controlled temporary R helper here; R syntax replaces the Stata do-file.

mark

Create an inclusion marker from a condition

Stata

mark touse if g == 2

R Package:base

data$touse <- as.integer(!is.na(data$g) & data$g==2)

markin

Find the row range enclosing a selected sample

Stata

markin if g == 2

R Package:base

selected <- which(data$g==2); interval <- range(selected)

Returns enclosing row endpoints only; selection can contain gaps and is not replaced by that interval.

markout

Clear an inclusion marker when variables are incomplete

Stata

markout touse x y

R Package:base

data$touse <- as.integer(data$touse==1 & stats::complete.cases(data[c('x','y')]))

marksample

Mark complete rows over supplied column names

Stata

syntax varlist
marksample touse

R Package:base

touse <- stats::complete.cases(data[vars])

R receives column names explicitly; no Stata syntax parser state or if/in qualifiers are read.

matlist

Format a numeric matrix for display

Stata

matlist X, format(%9.2f)

R Package:base

format(X,nsmall=2,trim=TRUE)

Differs from Stata Returns a character matrix; R does not duplicate Stata’s borders/equation headers.

matname

Name matrix columns

Stata

matname X first second, columns(1..2)

R Package:base

colnames(X) <- c('first','second')

Fixed workflow example; adapt the object and column names together.

mkmat

Create a matrix from selected numeric variables

Stata

mkmat x y, matrix(X)

R Package:base

X <- as.matrix(data[c('x','y')])

Differs from Stata X is the fixed matrix object name; R row names need not match Stata r1, r2 labels.

Create a matrix after listwise missing exclusion

Stata

mkmat x y, matrix(X) nomissing

R Package:base

X <- as.matrix(data[stats::complete.cases(data[c('x','y')]),c('x','y')])

numlist

Expand a numeric list with a fixed step

Stata

numlist "1(2)9"

R Package:base

values <- seq(1,9,by=2)

Constructs this list directly; it does not parse arbitrary Stata numlist strings.

Expand a decreasing consecutive numeric list

Stata

numlist "5/1"

R Package:base

values <- seq(5,1,by=-1)

Direct R sequence workflow for the displayed Stata list.

post

Append one result observation

Stata

post handle (1) (2.5)

R Package:base

results <- rbind(results,data.frame(id=1L,value=2.5))

Appends to the R accumulator; a separate save writes the final file.

postclose

Persist an accumulated result table

Stata

postclose handle

R Package:base

saveRDS(results,path)

Finalizes the R accumulator as RDS rather than closing a Stata postfile handle.

postfile

Initialize a typed result accumulator

Stata

postfile handle id value using results.dta, replace

R Package:base

results <- data.frame(id=integer(),value=double())

R accumulator workflow: append rows, then save separately; no disk handle is opened yet.

query

Inspect current R output settings

Stata

query output

R Package:base

options()[c('width','digits','scipen')]

Read-only R settings query; these are R-specific options rather than Stata parameter names.

require

Require an installed R workflow dependency

Stata

require ftools

R Package:base

stopifnot(requireNamespace('dplyr',quietly=TRUE))

Checks the R counterpart dependency dplyr; no package is installed and Stata package names do not translate automatically.

Require a minimum version of an R workflow dependency

Stata

require ftools >= 2.48.0

R Package:base

stopifnot(requireNamespace('dplyr',quietly=TRUE),utils::packageVersion('dplyr') >= '1.1.0')

The R counterpart has its own version requirement; 1.1.0 supports the .by and relationship features used in these examples.

sleep

Pause execution using milliseconds converted to seconds

Stata

sleep 1

R Package:base

Sys.sleep(0.001)

R Sys.sleep takes seconds; no machine-speed timing assertion is made.

svmat

Convert matrix columns to named variables

Stata

svmat X, names(col)

R Package:base

data <- as.data.frame(X)

Differs from Stata Creates a new table; merging with an existing dataset requires an explicit row/key alignment.

syntax

Validate a numeric column argument and an optional scalar

Stata

syntax varname(numeric) [, Scale(real 1)]

R Package:base

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 }

Uses R formals and explicit checks; it does not parse Stata’s command grammar.

sysdir

Inspect R installation and temporary directories

Stata

sysdir list

R Package:base

list(home=R.home(),library=R.home('library'),temporary=tempdir())

Shows R directories; Stata BASE/PLUS/PERSONAL directories have no one-to-one mapping.

tempfile

Reserve a unique temporary path

Stata

tempfile cache

R Package:base

path <- tempfile(fileext='.rds')

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.

tempname

Use a temporary scalar inside local scope

Stata

tempname total
scalar `total' = 10

R Package:base

local({ total <- 10; total*2 })

Lexical scope supplies isolation rather than a unique Stata temporary object name.

tempvar

Compute with a temporary vector in a local scope

Stata

tempvar squared
generate `squared' = x^2

R Package:base

local({ squared <- data$x^2; sum(squared,na.rm=TRUE) })

R local scope avoids adding a temporary dataset column; no Stata macro name is generated.

tokenize

Tokenize a quoted phrase and a word

Stata

tokenize "alpha beta" gamma

R Package:base

tokens <- scan(text='"alpha beta" gamma',what=character(),quiet=TRUE)

Differs from Stata Demonstrates basic double-quoted whitespace tokens; Stata compound quoting has no automatic equivalent.

Split simple whitespace-separated tokens

Stata

tokenize alpha beta gamma

R Package:base

tokens <- strsplit('alpha beta gamma',' +')[[1]]

Differs from Stata R returns a character vector instead of positional local macros; quoted-token parsing differs.

unab

Resolve an unambiguous abbreviated column name

Stata

unab vars : income

R Package:base

vars <- names(data)[pmatch('income',names(data),duplicates.ok=FALSE)]; stopifnot(!anyNA(vars))

R partial matching must be requested explicitly; exact matches take precedence.

Expand a column-name prefix wildcard

Stata

unab vars : x*

R Package:base

vars <- grep('^x',names(data),value=TRUE)

Handles the displayed simple prefix wildcard; this is not a complete Stata varlist parser.

unabcmd

Resolve a unique abbreviation among known R choices

Stata

unabcmd gen

R Package:base

full <- match.arg('mea',c('mean','median','sum'))

Illustrates explicit R-choice matching, not translation of Stata command abbreviations; Stata gen corresponds to generate.

viewsource

Inspect the body of a named R function

Stata

viewsource mean.ado

R Package:base

body(base::mean.default)

Reads an R function body rather than opening a Stata ado source editor.