如何在stata中巧妙地将协方差表转换成一对一?

时间:2015-04-24 11:44:16

标签: stata data-manipulation

我在使用Stata时遇到了关于数据管理的实际问题。我打算做的是在中国的30个省会城市(因此大致有870个相同的价值观)之间创建球形距离变量。有一些用户编写的命令来处理这个问题(通过谷歌地图)但我的问题是,由于某些保密的原因,数据存储在一个与互联网断开连接的独立计算机上,所以我必须定义所有的 - do-file中的to-one distance值,然后将它们合并到数据中。鉴于非工作性工作量(虽然不是真的不可行),我想知道是否有一些聪明的方法来完成这项工作。我有一个excel工作表,其中距离就像一个协方差martrix,省首都的名字出现在第一行和第一列,它就像一个下三角矩阵,。代表值

test = df[np.abs(df.Cost-df.Cost.mean())<=(3*df.Cost.mad())]

我知道如何导入这样的martrix,但我可以生成所需的一对一对吗?谢谢。

1 个答案:

答案 0 :(得分:0)

感谢@Roberto的有用建议,我已经部分解决了这个问题,我提出了我的解决方案,让任何可能遇到类似问题的新人受益,并希望从真正的专家那里获益,以改善我的代码

//import data from excel file
import excel using distance.xls
*********************************
* rename the variable name
* (to make it more well orgnized to facilitie use of --reshape-- command
*********************************
* rename the first column
ren A id
* rename the following variables
local i=0
foreach var of varlist B-AF {
    local j=`i'+1
    local i=`i'+1
    ren `var' distance`j'
}

*********************************
* reshape the data
*********************************
reshape long distance,i(id) j(city)
tostring city,replace
***the following part is really urgly, because I don't know how 
*to gen a one-to-one mapping between orginal province name and
*the new generated variable name like distance`j',I have to recover
*them by hand, I hope someone can help me to improve this part**
replace city="北京" if city=="1"
replace city="天津" if city=="2"
replace city="河北" if city=="3"
replace city="山西" if city=="4"
replace city="内蒙古" if city=="5"
replace city="辽宁" if city=="6"
replace city="吉林" if city=="7"
·····