将字符串变量转换为数字

时间:2018-06-17 19:16:27

标签: stata

我有一个字符串变量:

* Example generated by -dataex-. To install: ssc install dataex
clear
input str10 location
"North"    
"North"    
"North"    
"NorthEast"
"NorthEast"
"NorthEast"
"NorthEast"
"NorthEast"
"NorthWest"
"NorthWest"
"SouthEast"
"SouthWest"
"SouthWest"
"SouthWest"
"SouthWest"
"SouthWest"
"SouthWest"
"SouthWest"
"SouthWest"
"SouthWest"
"SouthWest"
"South"    
"South"    
"South"    
"South"    
end

当我尝试创建数字变量时:

destring location, replace

我收到以下错误:

  

location:包含非数字字符;没有替换

我做错了什么?

1 个答案:

答案 0 :(得分:2)

看起来您想要创建一个具有每个值的频率的数字变量。

为此,您需要使用encode命令:

. encode location, generate(new_location)

. tabulate new_location

new_locatio |
          n |      Freq.     Percent        Cum.
------------+-----------------------------------
      North |          3       12.00       12.00
  NorthEast |          5       20.00       32.00
  NorthWest |          2        8.00       40.00
      South |          4       16.00       56.00
  SouthEast |          1        4.00       60.00
  SouthWest |         10       40.00      100.00
------------+-----------------------------------
      Total |         25      100.00