Announcement

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

  • For loop

    Hi all,
    I am having some difficulty trying to use the for function (i am very new to stata). Below is a photo of my dataset, i wish to create a for loop that goes through each value in the variable 'beta_values' and to identify outliers. If the beta value is greater than 2 or less than -2, i want to display the ID of that company (using the id variable) 'has a beta value of' followed by the beta.
    Thanks.
    Click image for larger version

Name:	Screenshot 2024-04-03 at 23.40.20.png
Views:	1
Size:	309.1 KB
ID:	1748814


  • #2
    Code:
    display "Observations with beta-values outside (-2,2):"
    list id beta_values if !inrange(beta_values, -2,  2)
    If having your descriptive string displayed on each line of the listing rather than just as a header is important, you could do this:
    Code:
    gen YourBadString = "Observations with beta-values outside (-2, 2)" if !inrange(beta_values, -2,  2)
    list id beta_values YourBadString if !inrange(beta_values, -2,  2)

    Before posting in the future, you'd do well to re-read the StataList FAQ for new members (tab at top left of the StataList window), with particular attention to the section on using the -dataex- command to show example data. Although your screenshot is somewhat readable in this case, in general screenshots are not popular on StataList because besides issues with readability, they don't make it easy for someone to test out an answer, which -dataex- does.

    Beyond that, your mention of -for- brings up a couple of issues: 1) First of all, like most data analysis programs, commands in Stata generally apply to all observations, so a loop over observations is almost never necessary. In that regard, you'll find it unnecessary to do the kind of things you might do with a data matrix or array in other programming languages; 2) Stata has two looping commands useful in other contexts (though not here), namely -forvalues- and -foreach-. There is an "ancient" -for- command, but is now essentially never used in Stata: See -help for-.

    Comment

    Working...
    X