I'm trying to write a loop where I have reporter and partner countries and country groupings as separate variables and want to collapse and create new variables. The local is the country groupings and then I've tried to loop but get "var not found". Anyone have advice? Thanks in advance.

local country_groups EU advanced advanced_no_US_EU advanced_no_Taiwan EMs EMs_no_PRC_RUS EMs_no_PRC developing other_middle_income non_advanced non_advanced_no_PRC middle_income middle_income_no_PRC

foreach var in local country_groups {
preserve
collapse (sum) trade_world trade_PRC trade_US trade_PRC_US total_trade total_trade_HS if x==1, by(HS_chapter year)
gen reporter="var"
*China trade share
gen trade_share_PRC=trade_PRC/trade_world
*US trade share
gen trade_share_US=trade_US/trade_world
*China trade/China+US trade
gen trade_share_PRC_US=trade_PRC/trade_PRC_US
save `x'_US_PRC, replace
}