How to generate a string variable out of a labeled numeric variable (Stata)?
Asked Answered
D

2

6

I have a variable state that takes integer values from 11 to 99. It is labeled.

How can I create a string variable stateString that would have string values without all those numeric values?

gen stateString = tostring(state)

doesn't do the trick.

Daughtry answered 23/6, 2013 at 8:3 Comment(0)
D
9

tostring isn't a function; it's a command, and in Stata the two are quite distinct. Nothing but guesswork leads to the syntax you tried.

tostring state, gen(stateString) 

should work. But tostring is just a wrapper for the function string() and

gen  stateString = string(state) 

should also work to get string variables.

But the string values would be "11", ... "99" and that's the wrong approach. Given the value labels, you are fine with having this variable as numeric.

If you really want a string variable, you need decode, not tostring.

decode state, gen(stateString) 

EDIT: The syntax tostring() would only work if tostring() were a function, which is not. The original answer thus explained why the OP's code was wrong, as well as explaining how to do it correctly. I spelled out in this edit how to use decode.

EDIT 2021: The function string() still works and is documented as before, but the function name strofreal() is now given prominence.

Designation answered 23/6, 2013 at 10:18 Comment(0)
I
1

You have to install Roger Newson's command sdecode (ssc install sdecode) and then it is just:

sdecode state, gen(stateString)
Infectious answered 25/9, 2014 at 23:36 Comment(1)
You do not need to do this. As already explained, there are more direct solutions using official code only.Designation

© 2022 - 2024 — McMap. All rights reserved.