2015-07-10 203 views
0

我正在尝试在stata中创建一个循环,该循环将有一个变量,而不是数字或本地宏作为上限。循环变量作为Stata的上限

例如,如果num_tests是上限,我想循环:

forval i = 1/num_tests{ 
    //Do things here 
} 

我试图做到这一点使用本地宏:

local j = num_tests 
forval i = 1/`j'{ 
    //Do stuff 
} 

然而,这只是工作的第一个观察,并没有继续迭代其他。基本上,我希望for循环按照num_tests变量的指定迭代一定次数。我知道我可以在循环中使用_N来完成此操作,并以这种方式访问​​这些值,但从我听说的这种方法效率极低并且不推荐。

更新:这是一些示例代码,如果这有帮助。 num_tests是数据集中的一个变量,其值保持在1到6之间,取决于观察值。所以如果num_tests对于一个给定的观察结果是三个,我会希望循环执行三次。

//Find results of only the first lab tests 
forval i = 1/num_tests{ 

    replace val = `i' if `i' > val 

    //Set tTG IgA results 
    replace ttg_iga_result = real(test_result_`i')/real(high_ref_range_`i') if performed_test_cd_`i' == "5003030" | performed_test_cd_`i' == "9503207" 

    //Set tTG IgG results 
    replace ttg_igg_result = real(test_result_`i')/real(high_ref_range_`i') if performed_test_cd_`i' == "5003025" | performed_test_cd_`i' == "9503200" 

    //Set regular IgA results - if variable is > 1, then the patient has low IgA levels 
    replace iga_result = real(test_result_`i') if performed_test_cd_`i' == "1002860" 
} 

任何帮助将不胜感激。

感谢您的时间, 内特

+0

在我看来,这是一个会从广泛的重塑你的数据方面的问题长。 – 2015-07-10 19:43:29

回答

0

最后我只是用_N,使其工作:

//Local to hold total number of observations 
local N = _N 
forval j = 1/`N' { 
    local num = num_tests[`j'] 

    forval i = 1/`num' { 

     //Set tTG IgA results 
     replace ttg_iga_result = real(test_result_`i')/real(high_ref_range_`i') in `j' if performed_test_cd_`i' == "5003030" | performed_test_cd_`i' == "9503207" 

     //Set tTG IgG results 
     replace ttg_igg_result = real(test_result_`i')/real(high_ref_range_`i') in `j' if performed_test_cd_`i' == "5003025" | performed_test_cd_`i' == "9503200" 

     //Set regular IgA results - if variable is > 1, then the patient has low IgA levels 
     replace iga_result = real(test_result_`i') in `j' if performed_test_cd_`i' == "1002860" 
    } 
}