How to extract unique strings from a macro?

╄→尐↘猪︶ㄣ 提交于 2019-12-11 03:14:29

问题


I'm trying to automate a reshape using Stata.

I have a series of variables measured yearly. They are all named varname_yy, where yy is a number referring to the year of measurement. I managed to extract all the stubs varname_ from the variables and to put them into a macro using the following code:

local stubs
foreach var of varlist `myvars' {
local stub = substr("`var'",1,length("`var'") - 2)
    local stubs `stubs' `stub'
}

The problem is that I end up with many repeated stubs in the stubs macro and this causes reshape to return an error message.

In R I would just ask for unique(stubs), but I couldn't find any such function in Stata.

My tentative solution is to do the following:

local uniquestubs
foreach stub in `stubs' {
    if !regexm("`uniquestubs'","`stub'") {
        local uniquestubs "`uniquestubs'" " `stub'"
    }
}

However, I can't get rid of the duplicates.

What is the correct way of doing it?


回答1:


Roberto Ferrer's comment to my question led me to the answer. Turns out that all I had to do was to use the following line:

 local uniquestubs: list uniq stubs

Unlike syntax for evaluating macros, manipulating macros requires the macro names, so I should not enclose stubs in ` and ' as it is usually done.



来源:https://stackoverflow.com/questions/23889499/how-to-extract-unique-strings-from-a-macro

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