Frank
Frank

Reputation: 66819

using return list macros with `: list' syntax

I have made a list of variable names and want to check which variables I have excluded. The final line of my best guess does not work because r(varlist) is 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 that I could do a clunky three-liner here:

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

I'm asking if there's a more concise (or otherwise better) way.

I've looked through the documentation at help macrolists and help return list.

Upvotes: 3

Views: 208

Answers (1)

Roberto Ferrer
Roberto Ferrer

Reputation: 11102

You could make your code a "clunky" two-liner if you conclude that you don't need to drop the local macro rvarlist. Locals just disappear on their own. I usually don't find the need to explicitly drop them, although I don't mean to say that this is never necessary.

I would worry more about your use of globals. Their use can have unintended effects because, unlike locals, they don't die out and can collide with other system/program name spaces. Use them only if you really know what you're doing

An alternative to your code may be the following, but you lose functionality if you're filtering 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 the user-written command findname (SSC by Nick Cox), you get back functionality and allows for direct generation of a local macro. The filtered variable list can be put into a local 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 corresponding help files and also Speaking Stata: Finding variables.

Upvotes: 3

Related Questions