0
votes

I am attempting to create a loop in stata that would have a variable, rather than a number or local macro, as the upper bound.

For instance, if num_tests was the upper bound of the loop that I wanted:

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

I attempted to do this using a local macro:

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

However, this only worked for the first observation, and did not continue iterating over the others. Basically, I want the for loop to iterate a certain number of times, as specified by the num_tests variable. I understand that I could probably do this using _N in a loop and accessing the values that way, but from what I have heard this is extremely inefficient and not recommended.

Update: Here is some sample code, if this is helpful. num_tests is a variable in the data set which holds a value of between 1 and around 6, depending on the observation. So if num_tests for a given observation was three, I would want the loop to execute three times.

//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" 
}

Any help would be greatly appreciated.

Thanks for your time, Nate

1
It seems to me this is a problem that would benefit from reshaping your data from wide to long. - user4690969

1 Answers

0
votes

I ended up just using _N to make it work:

//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" 
    }
}