Search code examples
maxstatastata-macros

Find max of specific list of columns from macro


I have declared a local macro that corresponds to several variable names in my Stata project:

local letters a b c d

I want to be able to generate a new variable using all variables in the macro letters:

gen highest_letter = max(`letters')

However, this doesn't work, and leads to the following error message:

a b c d not found 

This is because max() requires that the input to be separated by commas like:

gen highest_letter = max(a, b, c, d)

Is there any way for me to manipulate the macro letters?

Or use a function other than max(), such that I can find the highest value in the list of variables without manually typing them into the max() function?


Solution

  • The egen function rowmax() doesn't require commas.

    egen highest_letter = rowmax(a b c d)
    

    As above, defining a local macro here is dispensable unless you want it for some other purpose. In any case, the problem here arises regardless of whether you use a macro; the problem, as you say, is the requirement of max() for comma-separated arguments.

    But given that you are using a macro

    local letters : subinstr local letters " " ",", all 
    

    is a way to insert the commas; it will work if and only if the names are separated by single spaces. If the real list of names is very long or you are writing a program or do file, it will be quicker than inserting commas manually.