Select variables and rows

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

drop

Drop rows meeting a condition

Stata

drop if x == 1

R Package:dplyr

filter(data, x != 1 | is.na(x))

Stata keeps rows with missing x here; | is.na(x) does the same in R.

Drop rows by position

Stata

drop in 1/4

R Package:dplyr

slice(data, -(1:4))

Drop a variable

Stata

drop x

R Package:dplyr

select(data, -x)
2 more examples and alternatives

Drop rows where x is missing

Stata

drop if missing(x)

R Package:dplyr

filter(data, !is.na(x))

Drop several variables

Stata

drop x1 x3-x5

R Package:dplyr

select(data, -c(x1, x3:x5))

Positions work too: select(data, -c(1, 3:5)).

duplicates

Drop rows that duplicate an earlier row

Stata

duplicates drop

R Package:tidystata

duplicates_drop(data)
1 more examples and alternatives

Keep the first row for each key

Stata

duplicates drop x1 x2, force

R Package:tidystata

duplicates_drop(data, x1, x2, .force = TRUE)

distinct(data, x1, x2, .keep_all = TRUE) is the dplyr version.

keep

Keep rows meeting a condition

Stata

keep if x1 == 1 & x2 == 2

R Package:dplyr

filter(data, x1 == 1 & x2 == 2)

filter() drops rows where the condition is NA, so rows with missing values never pass.

Keep the first rows

Stata

keep in 1/10

R Package:base

head(data, 10)

Keep some variables

Stata

keep x1 x3-x5

R Package:dplyr

select(data, x1, x3:x5)

Numbers select by position: select(data, 1, 3:5). select_or_transmute() also computes new columns.

6 more examples and alternatives

Keep rows where x is observed

Stata

keep if !missing(x)

R Package:dplyr

filter(data, !is.na(x))

Keep rows with listed values

Stata

keep if inlist(x, 1, 3, 5)

R Package:dplyr

filter(data, x %in% c(1, 3, 5))

Keep rows within a range

Stata

keep if inrange(x, 5000, 10000)

R Package:dplyr

filter(data, between(x, 5000, 10000))

Keep the last rows

Stata

keep in -10/-1

R Package:base

tail(data, 10)

Keep rows by position

Stata

keep in 7/12

R Package:dplyr

slice(data, 7:12)

Keep variables matching Stata wildcards

Stata

keep x*

R Package:tidystata

select(data, varlist("x*"))

sample

Reproducible random 10% sample

Stata

set seed 2024; sample 10

R Package:tidystata

data |> slice_sample(prop = 0.1) |> set_seed(2024)

Differs from Stata R and Stata use different random-number streams; the same numeric seed does not reproduce the same draws or selected rows.

Reproducible random sample of 1000 rows

Stata

set seed 2024; sample 1000, count

R Package:tidystata

data |> slice_sample(n = 1000) |> set_seed(2024)

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.