Using return list macros with the syntax `: list '

I have created a list of variable names and want to check which variables I have excluded. The last line of my best guess does not work because it is r(varlist)

not a macro name:

input abc bca cba
1 1 1
end

global mykeeps abc cba

ds
di "`: list local(r(varlist)) - global(mykeeps)'"

      

I know I could do a clumsy three-line here:

local rvarlist "`r(varlist)'"
di "`: list rvarlist - global(mykeeps)'"
macro drop rvarlist

      

I am asking if there is a shorter (or otherwise better) way.

I have looked at the documentation in help macrolists

and help return list

.

+3


source to share


1 answer


You can make your code "awkward" in two lines if you conclude that you don't need to discard the local macro rvarlist

. The locals simply disappear on their own. I usually don't see the need to explicitly drop them, although I don't mean to say that it should never be.

I would be more worried about your use of global

s. Their use can have unintended effects because, unlike local

s, they do not die out and may collide with other system / program namespaces. Use them only if you really know what you are doing.

An alternative to your code could be the following, but you lose functionality if you filter out variables with ds

:

clear 
set more off

input abc bca cba
1 1 1
end

local mykeeps abc cba
unab myvars: _all

di "`:list myvars - mykeeps'"

      



If you install a custom command findname

(SSC by Nick Cox), you get the functionality and allow for direct local macro creation. The filtered list of variables can be placed in the local address directly:

clear 
set more off

input abc bca cba
1 1 1
end

local mykeeps abc cba
findname, local(myvars)

di "`:list myvars - mykeeps'"

      

See the related help files as well as Speaking Stata: Searching for Variables .

+3


source







All Articles