1
votes

I'm puzzled by a weird error message when I use foreach loop in Stata.

I collect a name list of several geographic names from one dataset and put them in three locals: county, city, muni. Then, I "match" them with certain names (parkname) in another dataset.

The first two work well, but for the last local macro muni, the foreach failed and threw a weird error message. However, as you can see, I don't add "too many" parentheses in the loop body: there are only two.

So what's the source of the problem? I highly suspect it stems from the way I construct the last local, but I cannot figure out the problem.

By the way, city1 to city4 refer to four city names in Chinese characters (Unicode), but because Stack Overflow doesn't allow Unicode characters I substitute them. I'm not sure if this fact has anything to do with the error message.

import excel province=A city=B county=C using geonamelist.xlsx, clear
*-------------------------
*  city and county list
*-------------------------
qui levelsof county   , local(county)
qui levelsof city     , local(city)
** the municipalities are classified as provincial unit
local muni "city1" "city2" "city3" "city4"

*--------------------------
*   Industry Park data
*--------------------------
// Import industry park namelist
import excel order=A province=C class=D parkname=E area_NDRC=F  ///
area_MLR=J batch=I using namelist1.xls, clear

drop in 1/1
tempfile provincial
save "`provincial'"

import excel order=A province=C class=D parkname=E area_NDRC=F  ///
area_MLR=J batch=I using namelist2.xls,clear

drop in 1/1
append using "`provincial'"



** Matching the county names
gen county = ""
foreach i of local county {
    qui replace county = "`i'"     if strpos(parkname,"`i'")>0
}
gen city   = ""
foreach i of local city   {
    qui replace city  =  "`i'"     if strpos(parkname,"`i'")>0
}
foreach i of local muni   {
    qui replace city  =  "`i'"     if strpos(parkname,"`i'")>0
}

sort order
1

1 Answers

2
votes

Nothing here is reproducible by us, as your example depends on files we don't have. Unfortunately I and (I suspect) many of the most active Stata users here don't read or speak Chinese any way.

As you say, there is no obvious difference in the syntax.

However, I advise against this:

. local muni "city1" "city2" "city3" "city4"

. mac li
<other stuff listed here> 
_muni:          city1" "city2" "city3" "city4

Stata strips the outer quotation marks as delimiters. You have real names there in practice, but either way you need compound double quotes of the form

local muni `" "city1" "city2" "city3" "city4" "' 

So my only guess is that the message you get is a side-effect of that macro definition.