Strings and dates

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

char

Create characters from ASCII codes

Stata

generate z = char(code)

R Package:base

data$z <- vapply(data$code,intToUtf8,character(1))

Differs from Stata Restricted to ASCII codes 1–127; extended-byte encodings are not Unicode code points.

clock

Text to a date-time

Stata

generate t = clock(s, "YMDhms")

R Package:lubridate

mutate(data, t = lubridate::ymd_hms(s))

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.

1 more examples and alternatives

Parse a date-time with an explicit UTC timezone

Stata

generate double z = clock(s, "YMDhms")

R Package:base

data$z <- as.POSIXct(data$s,format='%Y-%m-%d %H:%M:%S',tz='UTC')

Differs from Stata POSIXct is seconds since 1970 with a timezone; Stata clock is milliseconds since 1960 without a timezone.

cofd

Convert R dates to Stata midnight millisecond codes

Stata

generate double z = cofd(d)

R Package:base

data$z <- as.numeric(data$d-as.Date('1960-01-01'))*86400000

Differs from Stata Returns ordinary Stata %tc milliseconds since 1960, not a POSIXct object.

date

Text to a date

Stata

generate d = date(s, "YMD")

R Package:lubridate

mutate(data, d = lubridate::ymd(s))

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.

3 more examples and alternatives

Parse day-month-year date strings

Stata

generate z = date(s, "DMY")

R Package:base

data$z <- as.Date(data$s,format='%d/%m/%Y')

Differs from Stata R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.

Parse month-day-year date strings

Stata

generate z = date(s, "MDY")

R Package:base

data$z <- as.Date(data$s,format='%m/%d/%Y')

Differs from Stata R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.

Parse year-month-day date strings

Stata

generate z = date(s, "YMD")

R Package:base

data$z <- as.Date(data$s,format='%Y-%m-%d')

Differs from Stata R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.

day

Day of the month

Stata

generate dd = day(d)

R Package:lubridate

mutate(data, dd = lubridate::day(d))
1 more examples and alternatives

Extract day-of-month numbers

Stata

generate z = day(d)

R Package:base

data$z <- as.integer(format(data$d,'%d'))

Differs from Stata Accepts an R Date column and returns the demonstrated calendar component; raw Stata date codes require conversion first.

daysinmonth

Get the number of days in each calendar month

Stata

generate z = daysinmonth(d)

R Package:lubridate

data$z <- as.integer(lubridate::days_in_month(data$d))

Differs from Stata R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.

display

Today’s date

Stata

display c(current_date)

R Package:base

Sys.Date()

dofc

Convert Stata millisecond datetimes to dates

Stata

generate z = dofc(milliseconds)

R Package:base

data$z <- as.Date(as.POSIXct(data$milliseconds/1000,origin='1960-01-01',tz='UTC'),tz='UTC')

Differs from Stata For ordinary Stata %tc values without leap-second encoding; UTC supplies a deterministic timezone.

dofm

First day of a monthly period

Stata

generate d = dofm(m)

R Package:tsibble

mutate(data, d = as.Date(m))

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.

1 more examples and alternatives

Convert Stata monthly codes to month-start dates

Stata

generate z = dofm(m)

R Package:base

data$z <- as.Date(sprintf('%04d-%02d-01',1960L+data$m%/%12L,data$m%%12L+1L))

Differs from Stata R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.

dofq

Convert Stata quarterly codes to quarter-start dates

Stata

generate z = dofq(q)

R Package:base

data$z <- as.Date(sprintf('%04d-%02d-01',1960L+data$q%/%4L,(data$q%%4L)*3L+1L))

Differs from Stata R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.

dofy

Construct the first day of each year

Stata

generate z = dofy(year)

R Package:base

data$z <- as.Date(sprintf('%04d-01-01',data$year))

Differs from Stata R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.

dow

Day of the week

Stata

generate w = dow(d)

R Package:lubridate

mutate(data, w = lubridate::wday(d) - 1)

wday() counts Sunday as 1; Stata’s dow() counts Sunday as 0.

1 more examples and alternatives

Extract weekday with Sunday coded zero

Stata

generate z = dow(d)

R Package:base

data$z <- as.integer(format(data$d,'%w'))

Differs from Stata Accepts an R Date column and returns the demonstrated calendar component; raw Stata date codes require conversion first.

doy

Extract day-of-year numbers

Stata

generate z = doy(d)

R Package:base

data$z <- as.integer(format(data$d,'%j'))

Differs from Stata Accepts an R Date column and returns the demonstrated calendar component; raw Stata date codes require conversion first.

firstdayofmonth

Find the first date of each calendar month

Stata

generate z = firstdayofmonth(d)

R Package:base

data$z <- as.Date(format(data$d,'%Y-%m-01'))

Differs from Stata R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.

format

Display a date

Stata

format d %td

R Package:base

format(data$d, "%d%b%Y")

Dates keep their class; format() only changes how they print.

generate

Age or duration in years

Stata

generate age = (d2 - d1) / 365.25

R Package:lubridate

mutate(data, age = lubridate::time_length(lubridate::interval(d1, d2), "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.

halfyear

Extract half-year numbers

Stata

generate z = halfyear(d)

R Package:base

data$z <- (as.integer(format(data$d,'%m'))-1L)%/%6L+1L

Differs from Stata Accepts an R Date column and returns the demonstrated calendar component; raw Stata date codes require conversion first.

hh

Extract the hour from a UTC timestamp

Stata

generate z = hh(t)

R Package:base

data$z <- as.integer(format(data$t,'%H',tz='UTC'))

Differs from Stata Input is an R POSIXct timestamp; convert raw Stata %tc numbers before extracting components.

lower

Lower case

Stata

generate s = lower(name)

R Package:stringr

mutate(data, s = str_to_lower(name))

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.

mdy

Date from year, month and day

Stata

generate d = mdy(m, d, y)

R Package:lubridate

mutate(data, d = lubridate::make_date(y, m, d))

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.

1 more examples and alternatives

Construct a date from year, month and day columns

Stata

generate z = mdy(month, day, year)

R Package:base

data$z <- as.Date(sprintf('%04d-%02d-%02d',data$year,data$month,data$day))

Differs from Stata R Date objects use a different numeric origin from Stata; use the object for calendar operations, not raw-code comparison.

mm

Extract the minute from a UTC timestamp

Stata

generate z = mm(t)

R Package:base

data$z <- as.integer(format(data$t,'%M',tz='UTC'))

Differs from Stata Input is an R POSIXct timestamp; uppercase %M means minute and lowercase %m means month.

mofd

Monthly period from a date

Stata

generate m = mofd(d)

R Package:tsibble

mutate(data, m = tsibble::yearmonth(d))

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.

1 more examples and alternatives

Convert Date values to Stata monthly codes

Stata

generate z = mofd(d)

R Package:base

data$z <- (as.integer(format(data$d,'%Y'))-1960L)*12L+as.integer(format(data$d,'%m'))-1L

Differs from Stata Returns numeric months since January 1960, explicitly using Stata monthly units.

month

Month of a date

Stata

generate m = month(d)

R Package:lubridate

mutate(data, m = lubridate::month(d))
1 more examples and alternatives

Extract month numbers

Stata

generate z = month(d)

R Package:base

data$z <- as.integer(format(data$d,'%m'))

Differs from Stata Accepts an R Date column and returns the demonstrated calendar component; raw Stata date codes require conversion first.

qofd

Quarterly period from a date

Stata

generate q = qofd(d)

R Package:tsibble

mutate(data, q = tsibble::yearquarter(d))

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.

1 more examples and alternatives

Convert Date values to Stata quarterly codes

Stata

generate z = qofd(d)

R Package:base

data$z <- (as.integer(format(data$d,'%Y'))-1960L)*4L+(as.integer(format(data$d,'%m'))-1L)%/%3L

Differs from Stata Returns numeric quarters since 1960q1, explicitly using Stata quarterly units.

quarter

Extract calendar quarter numbers

Stata

generate z = quarter(d)

R Package:base

data$z <- (as.integer(format(data$d,'%m'))-1L)%/%3L+1L

Differs from Stata Accepts an R Date column and returns the demonstrated calendar component; raw Stata date codes require conversion first.

real

Text to a number

Stata

generate x = real(s)

R Package:base

mutate(data, x = as.numeric(s))

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.

1 more examples and alternatives

Parse a controlled decimal grammar with missing for invalid text

Stata

generate z = real(s)

R Package:base

valid <- grepl('^[+-]?[0-9]+([.][0-9]+)?$',data$s); data$z <- rep(NA_real_,length(valid)); data$z[valid] <- as.numeric(data$s[valid])

Differs from Stata Deliberately limited grammar avoids accidental warnings; scientific notation and tagged missing require extension.

regexm

Match a regular expression

Stata

generate has = regexm(name, "^A")

R Package:stringr

mutate(data, has = str_detect(name, "^A"))

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.

1 more examples and alternatives

Flag strings containing only ASCII digits

Stata

generate z = regexm(s, "^[0-9]+$")

R Package:base

data$z <- as.integer(grepl('^[0-9]+$',data$s))

Differs from Stata This simple shared regex is portable; Stata and R regex engines differ for advanced patterns.

regexr

Replace the first regular-expression match

Stata

generate s = regexr(name, "[0-9]+", "")

R Package:stringr

mutate(data, s = str_replace(name, "[0-9]+", ""))

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.

1 more examples and alternatives

Replace the first numeric run in text

Stata

generate z = regexr(s, "[0-9]+", "#")

R Package:base

data$z <- sub('[0-9]+','#',data$s)

Differs from Stata First-match regex replacement; advanced regex features differ across engines.

regexreplaceall

Replace all numeric runs in text

Stata

generate z = regexreplaceall(s, "[0-9]+", "#")

R Package:base

data$z <- gsub('[0-9]+','#',data$s)

Differs from Stata StataNow regexreplaceall workflow with a simple ASCII pattern; older Stata versions use other functions.

regexs

Extract the matching text

Stata

generate d = regexs(1) if regexm(name, "([0-9]+)")

R Package:stringr

mutate(data, d = str_extract(name, "[0-9]+"))

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.

1 more examples and alternatives

Extract the first capturing group

Stata

generate z = regexs(1) if regexm(s, "([A-Z]+)-([0-9]+)")

R Package:stringr

data$z <- stringr::str_match(data$s,'([A-Z]+)-([0-9]+)')[,2]

R returns the group directly without a prior global regex-match state; unmatched rows use NA.

split

Split text into several variables

Stata

split name, parse(" ")

R Package:tidyr

separate_wider_delim(data, name, delim = " ", names_sep = "_", too_few = "align_start")
2 more examples and alternatives

Split two numeric fields and convert their types

Stata

split s, parse("-") destring

R Package:tidyr

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)

Differs from Stata Requires exactly two clean integer fields; resulting column names s1 and s2 are fixed.

Split two-component delimited strings

Stata

split s, parse("-") generate(part)

R Package:base

parts <- strsplit(data$s,'-',fixed=TRUE); data$part1 <- vapply(parts,`[`,character(1),1); data$part2 <- vapply(parts,`[`,character(1),2)

Differs from Stata Fixed two-field example with exactly one delimiter per row; generated stub part is fixed.

ss

Extract seconds from a UTC timestamp

Stata

generate z = ss(t)

R Package:base

data$z <- as.numeric(format(data$t,'%OS',tz='UTC'))

Differs from Stata Input is an R POSIXct timestamp; fractional-second precision depends on the platform and display settings.

string

Number to text

Stata

generate s = string(x)

R Package:base

mutate(data, s = as.character(x))

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.

stritrim

Collapse repeated spaces

Stata

generate s = stritrim(name)

R Package:stringr

mutate(data, s = str_squish(name))

Differs from Stata str_squish() also removes leading and trailing spaces.

1 more examples and alternatives

Collapse repeated internal ASCII spaces

Stata

generate z = stritrim(s)

R Package:base

data$z <- gsub(' +',' ',data$s)

strlen

Length of a string

Stata

generate n = strlen(name)

R Package:stringr

mutate(data, n = str_length(name))

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.

1 more examples and alternatives

Count bytes rather than Unicode characters

Stata

generate z = strlen(s)

R Package:base

data$z <- nchar(data$s,type='bytes')

Differs from Stata Byte length depends on encoding; this fixture is explicitly UTF-8.

strlower

Lower case

Stata

generate s = strlower(name)

R Package:stringr

mutate(data, s = str_to_lower(name))

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.

1 more examples and alternatives

Lowercase ASCII text

Stata

generate z = strlower(s)

R Package:base

data$z <- tolower(data$s)

strltrim

Trim leading ASCII spaces only

Stata

generate z = strltrim(s)

R Package:base

data$z <- sub('^ +','',data$s)

strmatch

Match a wildcard pattern

Stata

generate m = strmatch(name, "A*")

R Package:utils

mutate(data, m = grepl(glob2rx("A*"), name))

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.

1 more examples and alternatives

Match a simple wildcard pattern

Stata

generate z = strmatch(s, "a*")

R Package:base

data$z <- as.integer(grepl(utils::glob2rx('a*'),data$s))

Differs from Stata Demonstrates * wildcard only; review escaping for more complicated patterns.

strofreal

Format a number as zero-padded text

Stata

generate z = strofreal(x, "%06.0f")

R Package:base

data$z <- sprintf('%06.0f',data$x)

strpos

Whether a string contains some text

Stata

generate has = strpos(name, "a") > 0

R Package:stringr

mutate(data, has = str_detect(name, fixed("a")))

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.

1 more examples and alternatives

Locate a literal ASCII substring with zero for absence

Stata

generate z = strpos(s, "cat")

R Package:base

position <- regexpr('cat',data$s,fixed=TRUE); data$z <- ifelse(position<0,0L,as.integer(position))

strproper

Title case

Stata

generate s = strproper(name)

R Package:stringr

mutate(data, s = str_to_title(name))

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.

1 more examples and alternatives

Capitalize words in English place names

Stata

generate z = strproper(s)

R Package:stringr

data$z <- stringr::str_to_title(data$s,locale='en')

Differs from Stata English locale example; punctuation and language-specific capitalization can differ.

strreverse

Reverse plain ASCII text

Stata

generate z = strreverse(s)

R Package:base

data$z <- vapply(strsplit(data$s,''),function(z) paste(rev(z),collapse=''),character(1))

strrtrim

Trim trailing ASCII spaces only

Stata

generate z = strrtrim(s)

R Package:base

data$z <- sub(' +$','',data$s)

strtoname

Turn text into a valid name

Stata

generate n = strtoname(s)

R Package:base

mutate(data, n = make.names(s))

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.

1 more examples and alternatives

Convert short ASCII text to Stata-style names

Stata

generate z = strtoname(s)

R Package:base

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)

Differs from Stata Demonstrated short ASCII names only; R syntactic names and Stata reserved names follow different rules.

strtrim

Remove leading and trailing spaces

Stata

generate s = strtrim(name)

R Package:stringr

mutate(data, s = str_trim(name))

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.

1 more examples and alternatives

Trim leading and trailing ASCII spaces

Stata

generate z = strtrim(s)

R Package:base

data$z <- trimws(data$s,whitespace=' ')

strupper

Upper case

Stata

generate s = strupper(name)

R Package:stringr

mutate(data, s = str_to_upper(name))

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.

1 more examples and alternatives

Uppercase ASCII text

Stata

generate z = strupper(s)

R Package:base

data$z <- toupper(data$s)

subinstr

Replace text

Stata

generate s = subinstr(name, "a", "b", .)

R Package:stringr

mutate(data, s = str_replace_all(name, fixed("a"), "b"))

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.

2 more examples and alternatives

Replace every literal occurrence

Stata

generate z = subinstr(s, "cat", "dog", .)

R Package:base

data$z <- gsub('cat','dog',data$s,fixed=TRUE)

Replace only the first literal occurrence

Stata

generate z = subinstr(s, "cat", "dog", 1)

R Package:base

data$z <- sub('cat','dog',data$s,fixed=TRUE)

subinword

Replace a complete word in simple ASCII text

Stata

generate z = subinword(s, "cat", "dog", .)

R Package:base

data$z <- gsub('\\bcat\\b','dog',data$s,perl=TRUE)

Differs from Stata Uses regular-expression word boundaries; delimiters and Unicode rules can differ from Stata.

substr

Part of a string

Stata

generate s = substr(name, 1, 3)

R Package:stringr

mutate(data, s = str_sub(name, 1, 3))

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.

3 more examples and alternatives

Extract the last three ASCII characters

Stata

generate z = substr(s, -3, .)

R Package:stringr

data$z <- stringr::str_sub(data$s,-3)

Extract an ASCII prefix by length

Stata

generate z = substr(s, 1, 3)

R Package:base

data$z <- substr(data$s,1,3)

Extract ASCII text using start and length

Stata

generate z = substr(s, 3, 2)

R Package:base

data$z <- substr(data$s,3,4)

Stata takes a length; base R substr takes an inclusive ending position.

uchar

Create characters from Unicode code points

Stata

generate z = uchar(code)

R Package:base

data$z <- vapply(data$code,intToUtf8,character(1))

upper

Upper case

Stata

generate s = upper(name)

R Package:stringr

mutate(data, s = str_to_upper(name))

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.

ustrlen

Count Unicode code points

Stata

generate z = ustrlen(s)

R Package:base

data$z <- nchar(data$s,type='chars')

Counts code points, not visible grapheme clusters.

ustrlower

Lowercase Unicode text with an explicit locale

Stata

generate z = ustrlower(s)

R Package:stringr

data$z <- stringr::str_to_lower(data$s,locale='en')

Differs from Stata The locale is explicitly English; choose the relevant locale for language-sensitive casing.

ustrnormalize

Normalize canonically equivalent Unicode text

Stata

generate z = ustrnormalize(s, "nfc")

R Package:stringi

data$z <- stringi::stri_trans_nfc(data$s)

Normalize compatibility Unicode characters

Stata

generate z = ustrnormalize(s, "nfkc")

R Package:stringi

data$z <- stringi::stri_trans_nfkc(data$s)

ustrpos

Locate a Unicode substring by code-point position

Stata

generate z = ustrpos(s, "猫")

R Package:base

position <- regexpr('\u732b',data$s,fixed=TRUE); data$z <- ifelse(position<0,0L,as.integer(position))

ustrregexm

Unicode-aware regular expression, ignoring case

Stata

generate has = ustrregexm(name, "^a", 1)

R Package:stringr

mutate(data, has = str_detect(name, regex("^a", ignore_case = TRUE)))

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.

1 more examples and alternatives

Detect Unicode letters

Stata

generate z = ustrregexm(s, "\p{L}+")

R Package:stringr

data$z <- as.integer(stringr::str_detect(data$s,'\\p{L}+'))

Differs from Stata ICU regex workflow; missing strings in R remain NA rather than empty Stata strings.

ustrregexra

Replace every ICU regex match

Stata

generate z = ustrregexra(s, "[0-9]+", "#")

R Package:stringr

data$z <- stringr::str_replace_all(data$s,'[0-9]+','#')

ustrregexrf

Replace the first ICU regex match

Stata

generate z = ustrregexrf(s, "[0-9]+", "#")

R Package:stringr

data$z <- stringr::str_replace(data$s,'[0-9]+','#')

ustrreverse

Reverse Unicode code-point order

Stata

generate z = ustrreverse(s)

R Package:stringi

data$z <- stringi::stri_reverse(data$s)

Differs from Stata Combining marks and grapheme clusters may require a different user-facing reversal rule.

ustrtrim

Trim Unicode whitespace

Stata

generate z = ustrtrim(s)

R Package:stringr

data$z <- stringr::str_trim(data$s)

ustrupper

Uppercase Unicode text with an explicit locale

Stata

generate z = ustrupper(s)

R Package:stringr

data$z <- stringr::str_to_upper(data$s,locale='en')

Differs from Stata Explicit English locale; locale-specific casing can differ from Stata defaults.

usubstr

Extract one Unicode code point by position

Stata

generate z = usubstr(s, 2, 1)

R Package:base

data$z <- substr(data$s,2,2)

R character indexing follows code points; this does not count grapheme clusters.

word

The first word of a string

Stata

generate w = word(name, 1)

R Package:stringr

mutate(data, w = stringr::word(name, 1))

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.

1 more examples and alternatives

Extract the second simple whitespace word

Stata

generate z = word(s, 2)

R Package:base

data$z <- vapply(strsplit(trimws(data$s),' +'),function(z) z[2],character(1))

Differs from Stata Simple unquoted words with at least two tokens; Stata quoted-word parsing is not reproduced.

wordcount

Number of words

Stata

generate n = wordcount(name)

R Package:stringr

mutate(data, n = str_count(name, "\\S+"))

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.

1 more examples and alternatives

Count simple whitespace-separated words

Stata

generate z = wordcount(s)

R Package:base

data$z <- ifelse(trimws(data$s)=='',0L,lengths(strsplit(trimws(data$s),' +')))

Differs from Stata Unquoted ASCII words only; quoted multiword phrases need a parser.

year

Year of a date

Stata

generate y = year(d)

R Package:lubridate

mutate(data, y = lubridate::year(d))

lubridate::month(), day() and wday() extract the other parts.

1 more examples and alternatives

Extract calendar years

Stata

generate z = year(d)

R Package:base

data$z <- as.integer(format(data$d,'%Y'))

Differs from Stata Accepts an R Date column and returns the demonstrated calendar component; raw Stata date codes require conversion first.

ym

Construct Stata monthly codes from year and month

Stata

generate z = ym(year, month)

R Package:base

data$z <- (data$year-1960L)*12L+data$month-1L

Differs from Stata Requires valid integer months 1–12; output uses Stata months since January 1960.

yq

Construct Stata quarterly codes from year and quarter

Stata

generate z = yq(year, quarter)

R Package:base

data$z <- (data$year-1960L)*4L+data$quarter-1L

Differs from Stata Requires valid integer quarters 1–4; output uses quarters since 1960q1.