Stata:比较两个数据集并删除不同的变量

Stata: compare two datasets and drop different variables

我有两个大数据集(每个都有 1000 多个变量),其中一个包含第二个的所有变量,外加额外的变量。我想获得所有这些附加变量的列表,然后删除它们并将一个数据集附加到另一个数据集。我已经尝试了命令 dta_equal,但在这里发现了同样的问题:http://www.stata.com/statalist/archive/2011-08/msg00308.html

我想 append, keep() 无法直接实现我想做的事情,即不能在删除附加变量的同时附加数据集,因为我必须在 keep() 选项中一个一个地手动输入变量,考虑到我的大型数据集,这是不现实的。

有什么办法可以解决这个问题吗?

这里有几个有用的 Stata 命令。

第一个例子中使用了unab命令来制作数据集中变量较少的列表。第二个和第三个示例使用 describe 命令获取当前不在内存中的数据集中的变量列表。

示例的最后一部分展示了如何使用扩展宏列表函数来获取公共变量列表和两个数据集不公共的变量集。

* simulate 2 datasets, one has more variables than the other
sysuse auto, clear
save "data1.dta", replace
gen x = _n
gen y = -_n
save "data2.dta", replace

* example 1: drop after append
use "data1.dta", clear
unab vcommon : *
gen source = 1
append using "data2.dta"
replace source = 2 if mi(source)
keep `vcommon' source

* example 2: drop first then append
clear
describe using "data1.dta", varlist short
local vcommon `r(varlist)'
use `vcommon' using "data2.dta", clear
gen source = 2
append using "data1.dta"
replace source = 1 if mi(source)

* example 3: append and keep on the fly
use "data1.dta", clear
unab vcommon : *
gen source = 1
append using "data2.dta", keep(`vcommon')
replace source = 2 if mi(source)

* use extended macro list functions to manipulate variable list
clear
describe using "data1.dta", varlist short
local vlist1 `r(varlist)'
describe using "data2.dta", varlist short
local vlist2 `r(varlist)'
local vcommon : list vlist1 & vlist2
local vinonly1 : list vlist1 - vlist2
local vinonly2 : list vlist2 - vlist1
dis "common variables = `vcommon'"
dis "variables in data1 not found in data2 = `vinonly1'"
dis "variables in data2 not found in data1 = `vinonly2'"