根据最近的 I/observation 生成一个变量
Generate a variable based on the most recent I/observation
我的数据目前在 Stata 中组织如下:
input str2 Country gdp_2015 gdp_2016 gdp_2017 imports_2016 imports_2017 exports_2016
"A" 11 12 13 5 6 8 5
"B" 11 . . 5 6 10 5
"C" 12 13 . 5 6 8 5
end
gen net_imports = (imports_2017-foodexport_2017)
gen net_imports_toGDP = (net_imports/gdpcurrent_2017)
该代码运行良好,但仅在一个国家/地区拥有 2017 年数据时才创建一个变量,但我想根据对 GDP 的最新观察,从本质上创建一个进口占 GDP 的比率。
您可以按如下方式简单地替换缺失的数据:
replace gdp_2016 = gdp_2015 if mi(gdp_2016)
replace gdp_2017 = gdp_2016 if mi(gdp_2017)
但是,更通用的方法是从将数据从宽改造成长开始:
reshape long gdp_ imports_ exports_, i(Country)
有关命令的更多详细信息,请参阅 help reshape
。 gdp_
等是将成为新变量名称的存根,i(Country)
设置标识符。
然后您可以使用时间序列变量在每个观察中向前填充:
encode Country, generate(Country_num
xtset Country_num _j
replace gdp_=l.gdp_ if mi(gdp_) & !mi(l.gdp_)
我的数据目前在 Stata 中组织如下:
input str2 Country gdp_2015 gdp_2016 gdp_2017 imports_2016 imports_2017 exports_2016
"A" 11 12 13 5 6 8 5
"B" 11 . . 5 6 10 5
"C" 12 13 . 5 6 8 5
end
gen net_imports = (imports_2017-foodexport_2017)
gen net_imports_toGDP = (net_imports/gdpcurrent_2017)
该代码运行良好,但仅在一个国家/地区拥有 2017 年数据时才创建一个变量,但我想根据对 GDP 的最新观察,从本质上创建一个进口占 GDP 的比率。
您可以按如下方式简单地替换缺失的数据:
replace gdp_2016 = gdp_2015 if mi(gdp_2016)
replace gdp_2017 = gdp_2016 if mi(gdp_2017)
但是,更通用的方法是从将数据从宽改造成长开始:
reshape long gdp_ imports_ exports_, i(Country)
有关命令的更多详细信息,请参阅 help reshape
。 gdp_
等是将成为新变量名称的存根,i(Country)
设置标识符。
然后您可以使用时间序列变量在每个观察中向前填充:
encode Country, generate(Country_num
xtset Country_num _j
replace gdp_=l.gdp_ if mi(gdp_) & !mi(l.gdp_)