提问人:blue.meadow 提问时间:9/20/2023 最后编辑:Nick Coxblue.meadow 更新时间:9/20/2023 访问量:21
具有构成其他全局宏的全局宏的 Foreach 循环
Foreach loop with a global macro that constitutes other global macros
问:
我想缩短以下代码。我该怎么做?从本质上讲,我想创建另一个全局调用,它将具有下面提到的全局宏:即 、 和 。total_wardlist
wardlist_01
wardlist_02
wardlist_03
wardlist_04
foreach x of global wardlist_01{
display "Checking for `x'"
replace name_colony6_wardname = "`x'" if (strpos(name_colony6, "`x'") > 0)
}
foreach x of global wardlist_02{
display "Checking for `x'"
replace name_colony6_wardname = "`x'" if (strpos(name_colony6, "`x'") > 0)
}
foreach x of global wardlist_03{
display "Checking for `x'"
replace name_colony6_wardname = "`x'" if (strpos(name_colony6, "`x'") > 0)
}
foreach x of global wardlist_04{
display "Checking for `x'"
replace name_colony6_wardname = "`x'" if (strpos(name_colony6, "`x'") > 0)
}
foreach x of global wardlist_05{
display "Checking for `x'"
replace name_colony6_wardname = "`x'" if (strpos(name_colony6, "`x'") > 0)
}
我尝试了以下代码,但它在应该进行更改时返回“0 实际更改”。请指教。
global total_wardlist wardlist_01 wardlist_02 wardlist_03 wardlist_04 wardlist_05
foreach x of global $total_wardlist{
display "Checking for `$x'"
replace name_colony6_wardname = "`$x'" if (strpos(name_colony5, "`$x'") > 0)
}
答:
0赞
Nick Cox
9/20/2023
#1
让我们撇开有经验的 Stata 程序员对全局宏的普遍厌恶和回避。一般建议是尽可能使用本地宏。
您可以遍历这些宏:
forval g = 1/4 {
foreach x of global wardlist_0`g' {
display "Checking for `x'"
replace name_colony6_wardname = "`x'" if (strpos(name_colony6, "`x'") > 0)
}
}
如果你愿意,我会缩进内部循环。
或者你可以先把它们组合起来:
global total_wardlist $wardlist_01 $wardlist_02 $wardlist_03 $wardlist_04
foreach x of global total_wardlist {
display "Checking for `x'"
replace name_colony6_wardname = "`x'" if (strpos(name_colony6, "`x'") > 0)
}
代码未检查,但相当自信。第二种解决方案在尝试的代码中显示两种错误。
下一个:如何执行制表循环?
评论