在Stata中,如何在foreach循环中正确使用if语句?

时间:2014-08-08 11:16:58

标签: loops foreach stata

我尝试使用if语句为在Stata中foreach循环内创建的图表指定正确的标签:

foreach major in var1 var2 {

    * conditional labelling
    if "`major'" == "var1" {
        local ytitle "title for var1"
    }
    else if "`major" == "var2" {
        local ytitle "title for var2"
    }

    di in red "____________"
    di in red "`major'"
    di in red "`ytitle'"
    di in red "____________"

}

本练习的输出是

____________
var1
should be var1
____________
____________
var2
should be var1
____________

我的问题是 - 为什么在第二个循环实例中本地没有变化?

1 个答案:

答案 0 :(得分:4)

这个例子有点令人困惑,因为"应该是"在输出中应该(可以这么说)"标题为",匹配代码。除此之外,你的错误是一个无与伦比的单引号。试试

foreach major in var1 var2 {

    * conditional labelling
    if "`major'" == "var1" {
       local ytitle "title for var1"
    }
    else if "`major'" == "var2" {
       local ytitle "title for var2"
    }

    di in red "____________"
    di in red "`major'"
    di in red "`ytitle'"
    di in red "____________"

}