Announcement

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

  • How to expand?

    Suppose that I have the following data:
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str4 name float price str12 date float d
    "A" 34 "2016-12-03" 20791
    "A" 39 "2016-12-06" 20794
    "A" 41 "2016-12-10" 20798
    "B" 33 "2015-3-01"  20148
    "B" 37 "2015-3-04"  20151
    "B" 36 "2015-3-08"  20155
    end
    format %td d
    I want to expand the data to obtain
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str4 name float price str12 date float d
    "A" 34 "2016-12-03" 20791
    "A" 34 "2016-12-06" 20792
    "A" 34 "2016-12-06" 20793
    "A" 39 "2016-12-06" 20794
    "A" 39 "2016-12-10" 20795
    "A" 39 "2016-12-10" 20796
    "A" 39 "2016-12-10" 20797
    "A" 41 "2016-12-10" 20798
    "B" 33 "2015-3-01"  20148
    "B" 33 "2015-3-04"  20149
    "B" 33 "2015-3-04"  20150
    "B" 37 "2015-3-04"  20151
    "B" 37 "2015-3-08"  20152
    "B" 37 "2015-3-08"  20153
    "B" 37 "2015-3-08"  20154
    "B" 36 "2015-3-08"  20155
    end
    format %td d
    I use
    Code:
    expand d - d[_n-1]
    sort name d
    bys name (d): replace d = d[_n-1]+1 if _n > 1
    But the observations on price are not what I had in mind. Basically, I want the price to remain the same until the next date that the price changes.
    Ho-Chuan (River) Huang
    Stata 17.0, MP(4)

  • #2
    I think this will do what you want.
    Code:
    sort name d // make sure they're sorted to begin with
    expand d[_n+1]-d if name[_n+1]==name
    sort name d // get the new ones sorted in with the old ones

    Comment


    • #3
      Originally posted by William Lisowski View Post
      I think this will do what you want.
      Code:
      sort name d // make sure they're sorted to begin with
      expand d[_n+1]-d if name[_n+1]==name
      sort name d // get the new ones sorted in with the old ones
      Dear William, Thanks a lot. It works well.
      Ho-Chuan (River) Huang
      Stata 17.0, MP(4)

      Comment

      Working...
      X