stata中,如果某一年行业代码全部缺失,那么若想将公司对应缺失的行业代码填充为该公司正确的所属行业(也就是将缺失的该公司行业代码填充为与该公司其他年份相同的行业代码),应该如何处理?请写出具体的代码
时间: 2024-10-17 22:03:41 浏览: 488
在Stata中,你可以使用`egen`命令结合`replace`或`if`语句来解决这个问题。假设你有一个名为`company_data`的数据集,其中包含`year`, `firm_id`, 和`industry_code`等变量,可以按照以下步骤操作:
首先,你需要确定每个公司的历史行业代码,这通常需要一个之前已经计算好的汇总表或者是另一个数据集。假设这个汇总表叫`firm_history`,并且包含`firm_id`和`historical_industry_code`。
1. 加载并合并数据:
```stata
use firm_history, clear
merge 1:1 firm_id using company_data
```
2. 使用`egen`创建一个新变量存储历史行业代码:
```stata
egen historical_industry = group(historical_industry_code)
```
3. 创建一个新的变量,用以表示当前行业代码是否缺失:
```stata
gen missing_industry = missing(industry_code)
```
4. 使用`replace`替换缺失的行业代码,条件是历史行业代码存在(即`!missing(historical_industry)`):
```stata
replace industry_code = historical_industry_code if missing_industry & !missing(historical_industry)
```
5. 检查结果:
```stata
summarize industry_code if missing_industry
```
阅读全文
相关推荐


















