STATA学习笔记:egen函数

STATA学习笔记:egen函数

1. egen

(1)mean()

webuse egenxmpl,clear
egen avg = mean(cholesterol)
gen deviation = chol - avg
browse

STATA学习笔记:egen函数

(2)median()

webuse egenxmpl2,clear
browse
by dcode, sort:egen medstay = median(los)
//根据dcode分组,并按照dcode大小排序,取los的中位数
browse

STATA学习笔记:egen函数

(3)group()

webuse egenxmpl6,clear
browse
egen racesex = group(race sex)
// Create racesex containing values 1, 2, ..., 
//for the groups formed by race and sex 
//and containing missing if race or sex are missing
browse

STATA学习笔记:egen函数

2. 例子:汇率加权计算

clear
      input firm country   exch     export 
            1 		1 	    8 	  	  60 
            1 		2 	    0.03 	  50 
            1 		3 	   10 	  	  80 
            2 		2 	    0.03 	  68 
            2 		4 	    3 	  	  80 
            3 		2 	    0.03 	  200 
            3 		3 	   10 	  	  90 
            3 		4 	    3 	  	  250 
            3 		5 	    1.1 	  120
      end
//【注】案例来源于连玉君老师STATA33讲
	  
//加权计算汇率,权重是企业对每个国家出口额占该企业出口总额的比重
//计算公式为EER== (x1^w1)*(x2^w2)*(x3^w3)...*(xn^wn)
//xi表示各国汇率 wi表示出口比重
//由于STATA处理连乘困难,转化思路,对EER取对数
//ln(EER)== w1*ln(x1) + w2*ln(x2) + w3*ln(x3) 

//第一步:对汇率取对数
gen lnexch = ln(exch)
//第二步:对每一个企业,分别计算他们的各国出口额占其出口总额的比重
bysort firm: egen weight = pc(export),prop
* pc(exp) [, prop]                                                                                                             (allows by varlist:)  
*returns exp (within varlist) scaled to be a percentage of the total, 
*between 0 and 100.  
*The prop option returns exp scaled to be a proportion of the total,
*between 0 and 1.
*第三步:计算weight和ln(exch)的乘积
gen wei_lnexch = weight*ln(exch)
*第四步:对每一个企业,将weight和lnexch的乘积加总起来  
bysort firm: egen sum_wei = total(wei_lnexch)
gen EER = exp(sum_wei)	

STATA学习笔记:egen函数

上一篇:在Eclipse中配置Tomcat服务器


下一篇:sublime插件Package Control的官网下载与安装。