How to loop through specific string values of a variable in Stata? -
i want loop through specific subset vector of string variable in stata. have data set like:
id country effect period 1 0.20 2 2 0.25 3 3 japan 0.37 2 4 germany 0.22 3 5 0.11 3 6 japan 0.43 1 7 ireland 0.30 1 ... i don't want loop through values of country-variable, through specific values, e.g. , japan. tried:
levelsof country if country=="us" | country=="japan", local(countrylev) levelsof period, local(periodlev) //periods 1,2,3,4 mat m = j(2,4,.) local i=1 local j=1 foreach x of local countrylev { foreach per of local periodlev { mat m[`i',`j']=`per' *2 local ++j mat m[`i',`j']=`per' *3 local ++j mat m[`i',`j']=`per' *3 local ++j mat m[`i',`j']=`per' *4 local ++i local j=1 } matrix list m } however loops through "japan"...
i have guess answer lies in data or code have represented dots. example, check trailing spaces such "us ".
for cycling on 2 distinct values, can direct ,
foreach c in japan { <stuff> if country == "`c'" } except (as above) trailing spaces undermine that. use trim() if spaces problem.
it easier map numeric variable , use distinct numeric values want. true when have blanks and/or other punctuation handle too. more, see (e.g.) this faq (which more relevant title implies; see method 1).
update
revised code makes matters more puzzling, not less. code seems boil down
mat m = j(2,4,.) forval = 1/2 { forval j = 1/4 { mat m[`i',`j']=`j'*2 mat m[`i',`j']=`j'*3 mat m[`i',`j']=`j'*3 mat m[`i',`j']=`j'*4 } } matrix li m as listing matrix each time around loop doesn't seem important.
indeed, example seems collapse 1 line
mat m = (2,3,3,4)' * (1,2,3,4) however, may have simplified important out of problem focus on problematic in terms of code.
Comments
Post a Comment