从变量名中删除中间字符

Ruc*_*rya 4 stata

我的变量名以一个下划线结尾,后跟一年的代码.

例如,我有以下内容:

clear 
set obs 1

foreach var in age_58 age_64 age_75 age_184 age_93 age99 {
    generate `var' = rnormal()
}

list
     +----------------------------------------------------------------------+
     |    age_58      age_64      age_75     age_184     age_93       age99 |
     |----------------------------------------------------------------------|
  1. |  .1162236   -.8781271    1.199268   -1.475732   .9077238   -.0858719 |
     +----------------------------------------------------------------------+
Run Code Online (Sandbox Code Playgroud)

我想将它们重命名为:

age58 age64 age75 age184 age93 age99
Run Code Online (Sandbox Code Playgroud)

如何_一次从所有变量名中删除?

我正在使用Stata版本11.

Pea*_*cer 27

在Stata 13及更高版本中,可以使用内置命令在一行中完成此操作rename.

只需要指定相关规则,其中可以包含通配符:

rename *_# *#

list

     +----------------------------------------------------------------------+
     |     age58       age64       age75      age184      age93       age99 |
     |----------------------------------------------------------------------|
  1. |  .1162236   -.8781271    1.199268   -1.475732   .9077238   -.0858719 |
     +----------------------------------------------------------------------+
Run Code Online (Sandbox Code Playgroud)

键入help rename group有关各种可用说明符的详细信息.


Nic*_*Cox 19

对于Stata 8,社区贡献的命令renvars提供了一个解决方案:

renvars age_*, subst(_)
Run Code Online (Sandbox Code Playgroud)

有关文档和下载,请参阅

. search renvars, historical

Search of official help files, FAQs, Examples, SJs, and STBs

SJ-5-4  dm88_1  . . . . . . . . . . . . . . . . .  Software update for renvars
        (help renvars if installed) . . . . . . . . .  N. J. Cox and J. Weesie
        Q4/05   SJ 5(4):607
        trimend() option added and help file updated

STB-60  dm88  . . . . . . . .  Renaming variables, multiply and systematically
        (help renvars if installed) . . . . . . . . .  N. J. Cox and J. Weesie
        3/01    pp.4--6; STB Reprints Vol 10, pp.41--44
        renames variables by changing prefixes, postfixes, substrings,
        or as specified by a user supplied rule
Run Code Online (Sandbox Code Playgroud)

对于2001年的论文,请参阅此.pdf文件.


Maa*_*uis 9

创建一些示例数据:

foreach var of varlist * {
    local newname : subinstr local var "_" "", all
    if "`newname'" != "`var'" {
        rename `var' `newname'
    }
}
Run Code Online (Sandbox Code Playgroud)

删除下划线:

foreach var of varlist * {
    local newname : subinstr local var "_" "", all
    if "`newname'" != "`var'" {
        rename `var' `newname'
    }
}
Run Code Online (Sandbox Code Playgroud)