string 如何从标记的数字变量(Stata)中生成字符串变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17258778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate a string variable out of a labeled numeric variable (Stata)?
提问by Buras
I have a variable state
that takes integer values from 11 to 99. It is labeled.
我有一个state
从 11 到 99 的整数值的变量。它被标记。
How can I create a string variable stateString
that would have string values without all those numeric values?
如何创建一个字符串变量stateString
,该变量将具有没有所有这些数值的字符串值?
gen stateString = tostring(state)
gen stateString = tostring(state)
doesn't do the trick.
没有用。
回答by Nick Cox
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
不是函数;这是一个命令,在 Stata 中,两者是截然不同的。只有猜测才会导致您尝试的语法。
tostring stateString, gen(state)
should work. But tostring
is just a wrapper for the function string()
and
应该管用。但tostring
只是函数的包装器string()
和
gen state = string(stateString)
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.
但是字符串值将是“11”,...“99”,这是错误的方法。给定值标签,您可以将此变量设为数字。
If you really want a string variable, you need decode
, not tostring
.
如果你真的想要一个字符串变量,你需要decode
,而不是tostring
。
decode stateString, gen(state)
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
.
编辑:语法tostring()
仅在tostring()
是函数时才有效,而不是。因此,原始答案解释了 OP 代码错误的原因,并解释了如何正确执行。我在此编辑中详细说明了如何使用decode
.
回答by victoria
You have to install Roger Newson's command sdecode
(ssc install sdecode
) and then it is just:
您必须安装 Roger Newson 的命令sdecode
( ssc install sdecode
),然后它就是:
sdecode state, gen(stateString)