Traci
Traci

Reputation: 101

Stata: wildcard with exceptions in egen functions

I am new to using macros, and I want to incorporate this "Wildcard with exceptions" syntax into an egen function in Stata 12. I would like to do something along the lines of this:

foreach i in E F G {
    unab all`i' : V_`i'*
    unab excl`i' : V_`i'9*
    local general`i' : list all`i' - excl`i'
} 

egen Exp_operating = rowtotal(`generalE')
egen Exp_capital = rowtotal(`generalF' `generalG') 

In words, I want to make a variable list of V_E* that excludes variables V_E9*, and then create a variable that is equal to the sum of each variable in that list for each observation. However, I get a syntax error after executing the egen command. Can someone help me figure out how to do what I want to do?

Upvotes: 1

Views: 903

Answers (1)

Roberto Ferrer
Roberto Ferrer

Reputation: 11102

Some code with technique:

clear all
set more off

*----- example data -----

set obs 1

gen V_E1 = 1
gen V_E2 = 2
gen V_E22 = 2
gen V_E3 = 3

gen V_F1 = 3
gen V_F2 = 4
gen V_F22 = 4
gen V_F3 = 5

*----- what you seek -----

foreach i in E F {
    unab all`i' : V_`i'*
    unab excl`i' : V_`i'2*
    local general`i' : list all`i' - excl`i'
} 

* display contents of macros 
display "`generalE'"
display "`generalE' `generalF'"

* sum of V_E1 V_E3
egen Exp_operating = rowtotal(`generalE')

* sum of V_E1 V_E3 V_F1 V_F3
egen Exp_capital = rowtotal(`generalE' `generalF') 

list

Use display to check the contents of macros before passing them on to egen.

Upvotes: 1

Related Questions