重塑长变量时出错

时间:2018-08-06 15:47:20

标签: syntax-error stata reshape stubs

我必须reshape从宽到长的数据集。我有500个变量,范围从2016年到2007年,并记录为abcd2016,依此类推。我需要一个过程,无需输入所有变量的名称即可reshape,然后运行:

unab vars : *2016 
local stubs16 : subinstr local vars "2016" "", all
unab vars : *2015 
local stubs15 : subinstr local vars "2015" "", all

以此类推,然后:

reshape long `stubs16' `stubs15' `stubs14' `stubs13' `stubs12' `stubs11' `stubs10' `stubs09' `stubs08' `stubs07', i(id) j(year)

但是我得到了错误

invalid syntax
r(198);

为什么?你能帮我解决吗?

1 个答案:

答案 0 :(得分:2)

想法是在重塑为长格式时仅指定存根。为此,您需要从变量名称中删除年份部分,并将唯一的存根存储在本地中,您可以将其传递给整形:

/* (1) Fake Data */
clear
set obs 100
gen id = _n
foreach s in stub stump head {
    forvalues t = 2008(1)2018 {
        gen `s'`t' = rnormal()
    }
}

/* (2) Get a list of stubs and reshape */
/* Get a list of variables that contain 20, which is stored in r(varlist) */
ds *20*
/* remove the year part */
local prefixes = ustrregexra("`r(varlist)'","20[0-9][0-9]","")
/* remove duplicates from list */
local prefixes: list uniq prefixes 
reshape long `prefixes', i(id) j(t)

这会将数字后缀存储在名为t的变量中。