Announcement

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

  • Calculate range of a variable

    Hi everyone

    Not sure if I am getting old but imagine I have a data set of individuals i and time points j and a variable x like this:

    Code:
    clear
    input i j x
    1 1 -1
    1 2  0
    1 3  1
    2 1  1
    2 2  1
    2 3  1
    end
    What's the best way to calculate the range of x within individuals i, like:

    Code:
    clear
    input i j x x_range
    1 1  0        2
    1 2 -1        2
    1 3  1        2
    2 1  1        0
    2 2  1        0
    2 3  1        0
    end
    Sorry if this is trivial and thanks for your consideration

  • #2
    The second method here works if and only if there are no missing values.

    Code:
    clear
    input i j x
    1 1 -1
    1 2  0
    1 3  1
    2 1  1
    2 2  1
    2 3  1
    end
    
    bysort i : egen max = max(x)
    by i: egen min = min(x)
    
    gen range = max - min 
    
    bysort i (x) : gen range2 = x[_N] - x[1]
    
    list, sepby(i)
    
         +-----------------------------------------+
         | i   j    x   max   min   range   range2 |
         |-----------------------------------------|
      1. | 1   1   -1     1    -1       2        2 |
      2. | 1   2    0     1    -1       2        2 |
      3. | 1   3    1     1    -1       2        2 |
         |-----------------------------------------|
      4. | 2   1    1     1     1       0        0 |
      5. | 2   2    1     1     1       0        0 |
      6. | 2   3    1     1     1       0        0 |
         +-----------------------------------------+

    Comment


    • #3
      Thanks so much!

      Comment

      Working...
      X