Announcement

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

  • Making foreach go through multiple variables but stops when one criteria is met

    Hi,
    I am trying to program a code that goes through variables pr1-25 (procedure codes) to create a new variable that corresponds to these codes prday1-prday25 where prday contains the day of the procedure performed.

    This is the code I am using
    gen time_procedure=.
    foreach x of numlist 1/25 {
    replace time_procedure=prday`x' if i10_pr`x' == "ddd" | i10_pr`x' == "ffff"
    }

    The issue is that through 1-25 there might be more than one procedure with ddd or ffff codes, so I want the code to run but stop replacing the days if it encountered further procedure through 25
    for example
    if pr1 is ffff it replaces the day with "5" which is the value in prday1
    if the same record has pr5 as ddd or ffff, it will replace the "5" with "10" which is the code in prday5
    I don't want that replace to happen, is there anyway to do that?



    Last edited by michael megaly; 14 Nov 2021, 09:07. Reason: foreach

  • #2
    If I understand you correctly, you can just condition your -replace- on time_procedure being missing:

    Code:
    replace time_procedure=prday`x' if (time_procedure !=.) & ( i10_pr`x' == "ddd" | i10_pr`x' == "ffff")

    Comment


    • #3
      Great solution Mike, but do you mean
      if time_procedure =.
      as we are conditioning on it being missing ?

      Comment


      • #4
        Yes. "To condition on" here means "perform some action conditional on something being true or not true." Here, you would replace the value of time_procedure on the condition of it not being missing, i.e., that it has not already received a value. As for this being a "great" solution, I appreciate the thanks, but I'd add that this is a very standard programming trick in situations like this in which you want to do something the first time some value is found and not do that something after that. It's worth adding to your back of tricks, as this situation appears in various contexts.

        Comment

        Working...
        X