Search code examples
stata

Transforming a variable from string to numeric


I'm trying to convert a binary variable from a string (e.g. "Male" or "Female") into binary (0 and 1). I tried with the following:

replace q1=1 if q1=="Female"

but I get the following error: type mismatch. What is the issue and how can I fix it?

Please note that I do not want to create a new variable, but only to conditionally replace values in the existing one.


Solution

  • I figured out the solution: turn it into a number of a type string and use the destring command.

    replace q1="1" if q1=="Female"
    destring q1, replace