在宏中保存 .dta 数据集中变量的存储类型(不打开它)

save in a macro the storage type of variables in a .dta dataset (without opening it)

我想在宏中保存 .dta 数据集中变量的存储类型(不打开它)。

作为示例,我将首先创建一个数据集 temp.dta

drop _all  
set obs 100
gen a = runiform()
save temp, replace

在交互式会话中,我可以使用命令 describe using

显示所有变量的存储类型

但是该命令只保存了数据集的维度,没有任何存储类型相关的信息。

有办法吗?

你可以从这个例子开始:

clear
set more off

sysuse auto

foreach v of varlist _all {
    local allt `allt' `v' `: type `v''
}

display "`allt'"

我设置的信息是每个变量名后面都有类型,但是你可以修改它以满足你的需要;也许两个本地人,一个有变量名,另一个有相应的类型最适合你。

关键是扩展宏函数 type varname。有关详细信息,请参阅 help extended_fcn

为此,数据集需要在某个时候打开。如果没有后一个要求,我不知道这样做的方法。

编辑

@SteveSamuels 提出 use <somedata> in 1,我提出基准:

clear

*----- example data -----

sysuse auto
expand 50000

tempfile myauto
save "`myauto'"

*----- tests -----

clear

timer on 1
describe using "`myauto'"
timer off 1

clear

timer on 2
use "`myauto'" in 1
describe
timer off 2

clear

timer on 3
use "`myauto'"
describe
timer off 3

count
timer list

timer clear
clear

导致

. timer list
   1:      0.00 /        1 =       0.0000
   2:      0.22 /        1 =       0.2190
   3:      0.33 /        1 =       0.3260

因此,正如预期的那样,它比简单的 use 更快,但 describe using ... 仍然赢得了比赛。后者必须使用优化的代码,此外,尽管只加载了一个观察值,但一定有某种原因 use <somedata> in 1 出乎意料地慢。

当然,这不包括循环变量和使用扩展宏函数,也不包括解析日志文件;但我认为结果不会有太大变化。