【问题标题】:Converting string to numeric in Stata在Stata中将字符串转换为数字
【发布时间】:2013-12-06 16:16:49
【问题描述】:

我有一个名为agen 的变量中的个人年龄调查数据。最初,变量是字符串,所以我使用encode 命令将其转换为数字。当我尝试生成一个新变量hhage引用户主年龄时,生成的新变量不一致。

我使用的命令如下:

encode agen, gen(age) 
gen hhage=age if relntohrp==1

生成的新变量并不一致,因为我浏览时:第一户人家户主的年龄是65岁,而新生成的数字是63岁。当我查看第二户时,变量hhage报告了28而不是 33 作为 housheold 头的头。以此类推。

【问题讨论】:

    标签: string stata


    【解决方案1】:

    运行help encode,你可以阅读:

    如果 varname 包含恰好存储的数字,则不要使用 encode 作为字符串;改为使用generate newvar = real(varname)destring; 参见 real() 或 [D] destring。

    例如:

    clear all
    set more off
    
    input id str5 age
    1 "32"
    2 "14"
    3 "65"
    4 "54"
    5 "98"
    end
    
    list
    
    encode age, gen(age2)
    destring age, gen(age3)
    
    list, nolabel
    

    注意使用encodedestring 之间的区别。前者将数字代码 (1, 2, 3, ...) 分配给字符串值,而destring 将字符串值转换为数字。当您list 时,您会看到剥离值标签:

    . list, nolabel
    
         +------------------------+
         | id   age   age3   age2 |
         |------------------------|
      1. |  1    32     32      2 |
      2. |  2    14     14      1 |
      3. |  3    65     65      4 |
      4. |  4    54     54      3 |
      5. |  5    98     98      5 |
         +------------------------+
    

    一个简单的listbrowse 可能会让您感到困惑,因为encode 分配了自然数序列,但也分配了等于原始字符串的值标签:

    . list
    
         +------------------------+
         | id   age   age3   age2 |
         |------------------------|
      1. |  1    32     32     32 |
      2. |  2    14     14     14 |
      3. |  3    65     65     65 |
      4. |  4    54     54     54 |
      5. |  5    98     98     98 |
         +------------------------+
    

    nolabel 选项显示“基础”数据。

    你提到它不一致,但对于未来的问题,发布准确的输入和结果对于那些试图帮助你的人更有用。

    【讨论】:

      【解决方案2】:

      试试看this 方法?听起来你可能在方法的某个地方出现了失误。

      【讨论】:

      • @Roberto Ferrer 的回答是准确的,我敢打赌。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 2019-10-10
      • 2014-02-25
      相关资源
      最近更新 更多