It might be the case that you have a lot of string variables in your dataset, although they are actually numeric. Why is this not desirable?
Well, statistical analysis is all about numbers. Accordingly, we want to convert string variables to numeric variables as far as possible (of course, this cannot be as easily fixed for variables that actually contain – and should contain – strings of text).
There are a couple of different ways that we can convert string variables to numeric variable. We will use a dataset called TestData2.dta, which looks like this:
describe |

list |

By reviewing the tables above, we can notice that three of the variables – sex2, srh2, and income2 are string variables although they actually could be numeric. This will make them rather impossible to use in statistical analysis. However, we need different approaches to actually convert them to numeric – described in detail below.
Real
The first alternative is to use real. This works for string variables that only contain numbers, such as sex2.
generate sex=real(sex2) |
This will create a new variable called sex, which is a numeric version of sex2.
describe sex sex2 |

More informationhelp real |
Destring
For sex2, we could have achieved the almost same result by using destring.
destring sex2, gen(sex) |
This too will create a new variable called sex, which is numeric version of sex2. An advantage is that we keep the variable label.
describe sex sex2 |

For the variable income2, it is not possible to use real at all, since this string variable contains non-numeric values (in this case, commas). If we use real, all cells that contain a non-numeric character will have missing values. Here our best option is to use destring, which allows us to ignore the non-numeric characters.
destring income2, gen(income) ignore(",") |
Let us further describe the two variables.
destring income2, gen(income) ignore(",") |

More informationhelp destring |
Encode
The third type of string variable that we want to convert to a numeric variable, is srh2. This variable, however, have the actual categories coded in the cells (i.e. Poor, Good, and Excellent). We want these translated into numbers instead. We can use encode to achieve this.
encode srh2, gen(srh) |
And then we can describe the variables.
describe srh srh2 |

| Note Stata automatically creates value labels for the new variable. |
More informationhelp encode |
Tostring and decode
Finally, sometimes we might want to convert numeric variables into string variables (e.g. to be able to use substring, see Substring).
According to the same principles as we used destring and encode, we can apply tostring and decode.
More informationhelp tostringhelp decode |