Announcement

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

  • Finding nearest value with specific conditions

    Hello all,
    I have attached a photo with a snippet from the dataset I am using. What I am trying to do is for the variables with the same "secid", same "datadate", same "exdate", same "strike_price", and same "cp_flag", find the variable (with the aforementioned conditions), which has the closest absolute value of "delta" to the number 0.5. I would then like to drop the other variables that are further away from 0.5. Those anyone have an idea regarding how this can be done?
    Thanks!

    Click image for larger version

Name:	Stata Help .png
Views:	1
Size:	20.1 KB
ID:	1662653



  • #2
    I assume you mean drop the other observations that are further away from 0.5.

    Code:
    gen deviance = abs(abs(delta) - 0.5)
    by secid datadate exdate cp_flag (deviance), sort: keep if _n == 1
    Note: because example data was provided in an unimportable form, this code is not tested. Beware of typos of other errors.

    In the future, when showing data examples, please use the -dataex- command to do so. If you are running version 17, 16 or a fully updated version 15.1 or 14.2, -dataex- is already part of your official Stata installation. If not, run -ssc install dataex- to get it. Either way, run -help dataex- to read the simple instructions for using it. -dataex- will save you time; it is easier and quicker than typing out tables. It includes complete information about aspects of the data that are often critical to answering your question but cannot be seen from tabular displays or screenshots. It also makes it possible for those who want to help you to create a faithful representation of your example to try out their code, which in turn makes it more likely that their answer will actually work in your data.

    Comment


    • #3
      Dear Clyde,

      Thank you for your answer. I tried your code and it seems to work. I will definitely use dataex next time. But could you tell me why you did not include the variable "strike_price" in the second line in your code (the by command).

      Thanks

      Comment


      • #4
        But could you tell me why you did not include the variable "strike_price" in the second line in your code (the by command).
        That was an error on my part. It should have been included. Just put it in there after cp_flag.

        Comment

        Working...
        X