重塑长多变量时出错

Error in reshape long multiple variables

我必须 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);

为什么?你能帮我修一下吗?

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

/* (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 的变量中。