encode
Turns a text column into numbered categories.
What we have
- text to numbered categories, in alphabetical order, with the words kept as value labels
Coming later
label()— accepted, but the label set is still named after the new variable
How you write it
encode strvar, generate(newvar)
Square brackets mean optional. A vertical bar means choose one.
What it does
Models cannot do arithmetic on the word "Kerala". encode state, generate(statenum) gives each distinct text value a number, in alphabetical order, and attaches the original words as value labels — so tables and charts still read "Kerala" while the model sees a number.
This is the command you want for text categories. destring is for something else entirely: text that is really a number.
Try it
Every example below was run after sysuse vira.sample02, clear.
. encode state, generate(statenum)
state: 6 categories numbered 1 to 6
The same thing in pandas and in R
pandas
codes = {level: i + 1 for i, level in enumerate(sorted(df["state"].unique()))}
df["statenum"] = df["state"].map(codes)
R
# no R form for `encode` yet -- see docs/r-equivalents.md
. tabulate statenum
statenum | Freq. Percent Cum.
-------------+------------------------------------
Bihar | 706 11.77 11.77
Gujarat | 991 16.52 28.28
Kerala | 1,031 17.18 45.47
Odisha | 1,232 20.53 66.00
Punjab | 1,067 17.78 83.78
Rajasthan | 973 16.22 100.00
-------------+------------------------------------
Total | 6,000 100.00
The same thing in pandas and in R
pandas
df["statenum"].value_counts().sort_index()
R
library(dplyr) df %>% count(statenum) %>% mutate(percent = 100 * n / sum(n)) # This R was run in a real R (4.6.1) and gave the same numbers.