Announcement

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

  • Select value based on distance across group

    Dear Statalist forum, in the hope to address a broader audience, I post my question in #11 from this thread (Moving average by groups - Statalist) here:

    In the following, I provide a data example that aims to explain:

    Code:
      
    clear
    input float(risk_level risk_aversion capital minimum_capital)
    1 .01   44 12.5
    1 .02   34 12.5
    1 .03 12.5 12.5
    1 .04 12.5 12.5
    1 .05   19 12.5
    2 .01   20   13
    2 .02   21   13
    2 .03   13   13
    2 .04   13   13
    2 .05   13   13
    3 .01   36   18
    3 .02   18   18
    3 .03   28   18
    3 .04   18   18
    3 .05   39   18
    end
    Here, my aim is to create a variable "riskaversion_min" that equals the risk_aversion value of the observation with the minimum value for "capital" within each risk-level. As you can see, for each risk level/within each group there are >1 observations that meet the minimum capital-value requirement.

    I am now wondering, if there is a possibility to always choose the value for risk_aversion, such that the distance between minimum "risk_aversion" values of two neighbouring groups/risk-levels is minimised.

    So, in this example "riskaversion_min" should equal 0.3 for risk-level 1 and 0.3 for risk-level 2, since these are the values for risk_aversion that correspond to observations that have a minimum for "capital" within their group, but at the same time minimise the distance between the "risk_aversion" values of two neighbouring groups.

    This code

    Code:
    bysort risk_level: gen riskaversion_min = cond(min(risk_aversion[_n-1] - risk_aversion[_n]) & capital==minimum_capital, risk_aversion, .)
    is technically wrong, but hopefully gives you an idea of what I have in mind.

    Thanks a lot!
    Last edited by Roman von Vorgestern; 24 Jan 2022, 10:53.
Working...
X