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

  • Replacing a data variable if data falls within a date range

    I have some data that was misclassified for a certain date range and would like to change using Stata. I am trying to change variable "type" to "3" for date range Dec 17, 2018 to Jan 10, 2019. Below is an example of how the data looks and the code I've tried. I also have a variable for date that is a string variable.

    input type date
    1, 03jan2018
    2, 05mar2019
    2, 25dec2018
    2, 01jan2019

    replace type = 3 if inrange(date, 17dec2018, 10jan2019)

  • #2
    Please use dataex as requested (FAQ Advice #12). If date is a numeric daily date variable, then your condition could be e.g.

    if inrange(date, mdy(12, 17, 2018), mdy(1, 10, 2019))

    if inrange(date, td(17dec2018), td(10jan2019))
    but syntax as in #1 won't work, which is presumably your implication.

    It's hard to get a good understanding of dates in Stata without reading

    help datetime


    • #3
      Thank you! Both worked.
      Since I had already formatted the dates in a prior step, I didn't think I needed to use option 1 or include the td in option 2. That's what was hanging me up.


      • #4
        All inrange() sees is something like 17dec2018 -- which is not a valid argument.

        Nothing in the inrange() syntax signals or implies that the second or third argument is tied to the first. If it were then something like

        if inrange(x, a, b) 
        would be illegal, but it is fine in principle. So, td() was introduced to use your kind of thought to Stata, or you can use some other relevant function.

        I often experiment with display expressions with scalar arguments where I know what the answer should be. Here something like

        . di inrange(mdy(9, 13, 2019), 13sep2019, 13sep2019)
        13sep2019 invalid name
        shows that the direction of thought is not working out. Stata's logic here is that 13sep2019 clearly isn't a number, so Stata will try it out as a name, and that doesn't work either.