R for Stata users

Numeric

Stata R
max(v1) max(v1)
min(v1) min(v1)
max(v1, v2) pmax(v1, v2)
min(v1, v2) pmin(v1, v2)
cond(v1 > 3, 0, 1) ifelse(v1 > 3, 0, 1)
nvals n_distinct
group interaction
tag row_number() == 1

The package statar also includes functions that correspond to the Stata commands count, mode, xtile and _pctile


Characters


Dates

Use the package lubridate to work with dates. To convert strings (of daily date) and integers (number of days with respect to origin) to daily dates, one can use the function ymd, mdy, etc:

library(lubridate)
ymd("1900-01-01")
mdy("03/01/1998")

Extract information on dates by using the lubridate function week, month, year

x <- mdy("03/01/1998")
week(x)
month(x)
year(x)

Add periods to date through the function weeks, months and years

x + days(1)
x + weeks(1)
x + months(1)

Round dates using the function floor_date or ceiling_date

floor_date(x, unit = "week")

The package statar defines classes for monthly, and quarterly dates, coded as elapsed periods since “01/01/190”. This allows to use simple arithmetic on quarters and months, similarly to Stata.

datem <- as.monthly(x)
datem
#> [1] "1998m2"
datem + 1
#> [1] "1998m3"