Labels
Start with the expanded example for each command. Open the variants for options and alternative R approaches. Read the qualifications before adapting the code.
decode
Turn labelled values into text
Stata
decode x, generate(str_x)R Package:tidystata
mutate(data, str_x = decode(x))encode
Turn text into labelled categories
Stata
encode str_x, generate(x)R Package:dplyr
mutate(data, x = factor(str_x))Differs from Stata factor() creates integer level indices with an R class; encode creates numeric codes with a separate value-label definition. Collation can change code ordering.
label
Label every value of a categorical variable
Stata
label define gender 1 "male" 2 "female"R Package:dplyr
mutate(data, gender = factor(gender, levels = 1:2, labels = c("male", "female")))In R a labelled categorical variable is usually a factor. Give levels explicitly so each code gets the right label.
Remove value labels
Stata
label drop yesnoR Package:haven
mutate(data, x = haven::zap_labels(x))Show the categories of a variable
Stata
label list xR Package:base
levels(data$x)For labelled data read with haven, use haven::print_labels(data$x).
Attach a value label to a variable
Stata
label values x yesnoR Package:haven
mutate(data, x = haven::labelled(x, yesno))Define the labels once, as yesno <- c(No = 0, Yes = 1), then attach them to any variable; factor() is the usual R alternative.
Label a variable
Stata
label variable x "Variable name"R Package:labelled
labelled::set_variable_labels(data, x = "Variable name")Labels read from Stata files are kept; variables() and codebook() display them.
1 more examples and alternatives
Label some values only
Stata
label define x 9 "Unknown" 10 "Refused"R Package:haven
mutate(data, x = haven::labelled(x, c(Unknown = 9, Refused = 10)))Partial value labels are rare in R; haven keeps them so they survive a round trip to Stata. tab() and codebook() show them.
notes
Attach a note to a variable
Stata
notes x: Collected in wave 2R Package:base
attr(data$x, "note") <- "Collected in wave 2"R has no notes system; an attribute or a comment in the script is the usual substitute.