Announcement

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

  • Keep nearest value

    I created a lpoly smooth over many values, something like this

    Code:
    lpoly y x, degree(0) gen(x_hat y_hat) nodraw n(100000000)
    Now I want to find the predictions at certain integers x, in my case 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100.

    How can I keep only the closest value x_hat for each integer in the list?


  • #2
    If you want to map 0-5 to 0, 6-15 to 10, 16-25 to 20 and so on, then

    Code:
    gen nearest= ceil((x_hat-5)/10)*10
    will do it. Then calculate absolute differences from the nearest value and keep the first observation. In case of ties, the code below picks in favor of the lower value, e.g., both 19 and 21 are mapped to 20, so the code will pick 19.

    Code:
    gen absdiff= abs(x_hat-nearest)
    bys nearest (absdiff x_hat): keep if _n==1
    Example:

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float x_hat
    27
     2
    44
     5
    12
     1
     7
    16
    21
    30
    end
    
    gen nearest= ceil((x_hat-5)/10)*10
    gen absdiff= abs(x_hat-nearest)
    bys nearest (absdiff x_hat): keep if _n==1
    Res.:

    Code:
    . gen nearest= ceil((x_hat-5)/10)*10
    
    .
    . l, sep(0)
    
         +-----------------+
         | x_hat   nearest |
         |-----------------|
      1. |    27        30 |
      2. |     2         0 |
      3. |    44        40 |
      4. |     5         0 |
      5. |    12        10 |
      6. |     1         0 |
      7. |     7        10 |
      8. |    16        20 |
      9. |    21        20 |
     10. |    30        30 |
         +-----------------+
    
    . gen absdiff= abs(x_hat-nearest)
    
    .
    . bys nearest (absdiff x_hat): keep if _n==1
    (5 observations deleted)
    
    . l
    
         +---------------------------+
         | x_hat   nearest   absdiff |
         |---------------------------|
      1. |     1         0         1 |
      2. |    12        10         2 |
      3. |    21        20         1 |
      4. |    30        30         0 |
      5. |    44        40         4 |
         +---------------------------+
    
    .
    9
    Last edited by Andrew Musau; 24 Mar 2023, 05:30.

    Comment

    Working...
    X