Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to use If else command within a loop.

    Hello everyone, I am back with another question. I have been trying to use if else statement in a loop and I am having some difficulty making it work. I will now explain the scenario.


    Scenario:

    I have noticed that the if else command in my loop is not working correctly. It gives the correct output for the first observation. However, for all the observations i > 1, the results are a copy of the results from the first observation. What am I doing wrong here?

    STATA Code:

    file open trail1 using trail1.txt, text write replace

    file write trail1 "*** For each article you will receive two options about the presence of disagreements. Your job is to read the article and resolve the disagreement. The answer that is incorrect should be starred." _n

    file write trail1 _n

    local N = _N

    forvalues i = 1 / `N' {

    foreach var of varlist model_cs model_ts model_tscs model_spatial model_other {
    if `var' == 1 {
    file write trail1 "replace `var' = 0 if paper_id == `= paper_id[`i']'" _n
    file write trail1 "replace `var' = 1 if paper_id == `= paper_id[`i']'" _n
    file write trail1 _n
    }
    else if `var' == 0 {
    file write trail1 _n
    }
    }
    }

    file close trail1



    Last edited by Leon Kockaya; 07 Feb 2023, 14:21.

  • #2
    As I don't understand what you are trying to do, I can't offer you a specific fix.

    The reason you are getting the same results for all values of `i' is because that is precisely what your -if-else- structure tells Stata to do.

    It is critical to distinguish the -if- conditions that appear at the end of a command, and apply to that single command only and restrict which observations that command acts on, from the -if- (and -if-else-) commands that govern blocks of commands and determine whether the entire block is executed or not. In the latter, which is what you have coded, if you mention the name of a variable (other than within quotes, so that you are telling Stata to base its decision on the name of the variable rather than its value), there are many possible values of `var' that you might mean--one for every observation in the data set. So, if you don't explicitly tell Stata which value to look at, it is interpreted as the value in the first observation. So it is just as if you wrote -if `var'[1] == 1-, which is going to be either true for all values of `i' or false for all values of `i' because it does not depend on `i'.

    Again, I'm not sure what you are trying to do here, but my hunch is that what you meant to write is -if `var'[`i'] == 1-. Similarly, if my hunch is correct, the -else- part should be -else if `var'[`i'] == 0-.

    Comment

    Working...
    X