Announcement

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

  • Generation of a new variable according to time

    Hello everyone,


    I have a time variable which is given as a difference. So if there is a starting date, say, 6/6/16. My days are represented by another date (different for different observations) minus 6/6/16. Therefore, the first week is represented by 7 and below. The second week is above 7 but below 14 etc.


    How do I generate a new variable which represents average price of each week?

    i.e, how can I generate Avweeklyprice on Stata?

    Price Time Avweeklyprice
    2 7 3.5
    6 12 7
    8 13 7
    2 22 2
    5 2 3.5
    Note: My actual data has time ranging from 30 to -15.

  • #2
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input byte(price time) float avweeklyprice
    2  7 3.5
    6 12   7
    8 13   7
    2 22   2
    5  2 3.5
    end
    
    gen int week = ceil(time/7)
    by week, sort: egen avg_weekly_price = mean(price)
    In the future, when showing data examples, please use the -dataex- command to do so. If you are running version 15.1 or a fully updated version 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.



    When asking for help with code, always show example data. When showing example data, always use -dataex-.

    Comment


    • #3
      Hi Clyde,


      Thank you for your detailed answer, and also for letting me know about -dataex-

      Your codes run perfectly. But what are the possible ways of starting the week count from 1 and not 0?


      Comment


      • #4
        I don't understand the question. The code shown will identify 1 through 7 as 1, 8 through 14 as 2, etc., just as you asked for. The only thing that will be called week 0 is if there is a day 0. But you do not want to count that as part of week 1, because then week 1 will be 8 days long!

        Comment

        Working...
        X