Announcement

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

  • Create variable difference from date

    Hi,


    I have a dataset with a weekly date variable and my explanatory variable X. The treatment in my dataset happens on the week of the 14/01/2010.

    I want to create a variable "difference" as shown below, which measures weeks from treatment.
    date x variable difference
    01/01/2010 5.0 -2
    07/01/2010 4.3 -1
    14/01/2010 2.6 0
    21/01/2010 6.0 1
    28/01/2010 9..8 2
    What is the best way to do this? I have tried a few manual ways but they seem to take very long and are extremely inefficient.

    Thank you very much in advance!



  • #2
    Please use dataex. (FAQ Advice #12). This data example is based on copy and paste from #1 and some engineering. You didn't mean what you typed for the xvariable, but that doesn't affect the question.


    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str4 xvariable byte difference float date
    "5.0"  -2 18263
    "4.3"  -1 18269
    "2.6"   0 18276
    "6.0"   1 18283
    "9..8"  2 18290
    end
    format %td date
    
    . gen wanted = (date - mdy(1, 14, 2010)) / 7
    
    . l
    
         +---------------------------------------------+
         | xvaria~e   differ~e        date      wanted |
         |---------------------------------------------|
      1. |      5.0         -2   01jan2010   -1.857143 |
      2. |      4.3         -1   07jan2010          -1 |
      3. |      2.6          0   14jan2010           0 |
      4. |      6.0          1   21jan2010           1 |
      5. |     9..8          2   28jan2010           2 |
         +---------------------------------------------+
    
    . gen wanted2 = round(wanted, 1)
    
    . l
    
         +-------------------------------------------------------+
         | xvaria~e   differ~e        date      wanted   wanted2 |
         |-------------------------------------------------------|
      1. |      5.0         -2   01jan2010   -1.857143        -2 |
      2. |      4.3         -1   07jan2010          -1        -1 |
      3. |      2.6          0   14jan2010           0         0 |
      4. |      6.0          1   21jan2010           1         1 |
      5. |     9..8          2   28jan2010           2         2 |
         +-------------------------------------------------------+
    The irregular spacing of dates in the data example raises a serious question about what exactly you want.

    Comment


    • #3
      Thank you, this worked!

      Comment

      Working...
      X