Announcement

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

  • compares two date variables

    Dear all:

    I woudl like to compare the two date variables date1 and date2, and if the date of the date1 variable exists, but the date of the date2 variable does not, delete the data of the date1 variable.
    On the contrary, if the date of the date2 variable exists, but the date of the date1 variable does not, delete the data of the date2 variable.
    Finally, the number of rows and dates should be the same for both date variables.

    Code:
    clear
    input int date1 float price1 int date2  float price2
    15006 1366.01  15006  1241.6
    15007 1373.47  15007  1219.87
    15008 1349.47  15010  1214.36
    15010 1106.46  15011  1208.43
    15011 1354.31  15012  1212.58
    15012 1352.26  15035  1134.36
    15034 1241.23  15036  1103.25
    15035 1234.18  . .
    end
    format %td date1 date2

    Click image for larger version

Name:	2023-01-14 上午10.56.45.png
Views:	1
Size:	23.5 KB
ID:	1697230


    The result I require is below:


    Code:
    clear
    input int date1 float price1 int date2  float price2
    15006 1366.01  15006  1241.6
    15007 1373.47  15007  1219.87
    15010 1106.46  15010  1214.36
    15011 1354.31  15011  1208.43
    15012 1352.26  15012  1212.58
    15035 1234.18  15035  1134.36
    end
    format %td date1 date2
    Click image for larger version

Name:	2023-01-14 上午10.58.10.png
Views:	1
Size:	19.9 KB
ID:	1697231



    Thank you very much in advance,

    Travis

  • #2
    Code:
    gen long obs_no = _n
    reshape long date price, i(obs_no)
    by date (_j), sort: drop if _N < 2
    drop obs_no
    by date (_j), sort: replace _j = _n
    reshape wide price, i(date) j(_j)
    Note: There is no clear point in having a date1 and date2 variable in the end result because they are always equal. So this code leaves you with a single date variable and the corresponding price1 and price2. If you really need two separate date variables, -clonevar- and -rename- are your friends.

    Comment


    • #3
      Clyde, I reallyappreciate it. You’re a lifesaver!

      Originally posted by Clyde Schechter View Post
      Code:
      gen long obs_no = _n
      reshape long date price, i(obs_no)
      by date (_j), sort: drop if _N < 2
      drop obs_no
      by date (_j), sort: replace _j = _n
      reshape wide price, i(date) j(_j)
      Note: There is no clear point in having a date1 and date2 variable in the end result because they are always equal. So this code leaves you with a single date variable and the corresponding price1 and price2. If you really need two separate date variables, -clonevar- and -rename- are your friends.

      Comment

      Working...
      X