Remove middle character from variable names

廉价感情. 提交于 2019-12-12 12:17:34

问题


I have variable names ending with an underscore (_), followed by a year code:

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 |
     +----------------------------------------------------------------------+

I would like to rename them into:

age58 age64 age75 age184 age93 age99

I know I can do this by renaming one variable at a time as follows:

rename age_58 age58
rename age_64 age64
rename age_75 age75
rename age_184 age184
rename age_93 age93

How can I remove the underscore from all the variable names at once?


回答1:


In Stata 13 and later versions, this can be done in one line using the built-in command rename.

One merely has to specify the relevant rules, which can include wildcard characters:

rename *_# *#

list

     +----------------------------------------------------------------------+
     |     age58       age64       age75      age184      age93       age99 |
     |----------------------------------------------------------------------|
  1. |  .1162236   -.8781271    1.199268   -1.475732   .9077238   -.0858719 |
     +----------------------------------------------------------------------+

Type help rename group for details on the various available specifiers.




回答2:


For Stata 8 up, the community-contributed command renvars offers a solution:

renvars age_*, subst(_)

For documentation and download, see

. 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

For the 2001 paper, see this .pdf file.




回答3:


You can loop over the variables using the macro extended function subinstr:

foreach var of varlist * {
    local newname : subinstr local var "_" "", all
    if "`newname'" != "`var'" {
        rename `var' `newname'
    }
}


来源:https://stackoverflow.com/questions/26017568/remove-middle-character-from-variable-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!