Announcement

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

  • Display text within quietly performing loop

    Hi

    I have a loop which goes through many Stata files & appends those that include a specific variable & ignores those that doesn't.

    I want the display to show a line of output "Variable exists" or "Variable does not exist" depending on whether it is there or not - I want this shown in different colours (black if the variable exists, red if it doesn't)

    I can get the error code to show the error ("Variable does not exist"), but am not sure how to get the success option ("Variable exists") to show.

    Do you have any suggestions?

    My code so far is:

    Code:
    clear
    save "$proc/building.dta", emptyok replace
    local files : dir "$data" files "*.dta"
    qui foreach file of local files {
        
        * use
        use `"$data/`file'"', clear
        gen source = `"`file'"'
        
        * confirm if variable (v001) exists
        capture confirm variable v001
        
        * action depending on whether v001 exists
        // if exists
        if !_rc {
            di as error "Variable exists"
            
            /* code here to refine datasets */
    
            // append to dataset
            sleep 1000
            append using "$proc/building.dta", force
            save "$proc/building.dta", replace    
        }
        // if does not exist, clear & loop again
        else {
            di as error "Variable does not exist"
            clear
        }
        
    }

    & as I said, it only displays "Variable does not exist" in red - but does not show the black "Variable exists"

    Thank you for any help!

  • #2
    See the output of help quietly to learn about noisily.

    Code:
    noisily di as error "Variable does not exist"

    Comment


    • #3
      While William's advice is good, you are nevertheless about to run into a longstanding Stata bug.

      It may be necessary both to display the text "noisily" and "as text" in order for it to show up in a color that's not red. (Stata text colors are a bit funky; this may appear as red/black or red/green depending on your theme.)

      Code:
      quietly forvalues i = 1/10 {
          
          capture assert mod(`i',2) == 0
          
          if !_rc {
              noisily display as text "`i' is even"
          }
          else {
              noisily display as error "`i' is odd"
          }
          
      }
      (The second noisily is unnecessary, as "as error" implies it. I just like symmetry.)

      Comment

      Working...
      X