Construct data
Start with the expanded example for each command. Open the variants for options and alternative R approaches. Read the qualifications before adapting the code.
expand
Repeat each row n times
Stata
expand nR Package:tidyr
uncount(data, n)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.
fillin
Add rows for every combination of values
Stata
fillin x1 x2R Package:tidyr
complete(data, x1, x2)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.
input
Type in a small dataset
Stata
input x yR Package:tibble
tibble(x = c(1, 2), y = c(3, 4))set
Start a dataset with a given number of rows
Stata
set obs 100R Package:tibble
data <- tibble(id = 1:100)