Announcement

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

  • Generate variable to subtract current value from previous value

    Hello. I am working with the NYT COVID-19 data. The data presents two years worth of COVID-19 case and death data. Each month presents the geographic unit's case and death load for that month plus the case and death loads from the previous months ex. (two new cases per month):
    ```
    Date Cases New_Cases
    1-20 0 0
    2-20 1 1
    3-20 3 2
    4-20 5 2
    5-20 7 2
    6-20 9 2
    ```
    Is there a way to generate a variable (New_Cases) to subtract the number of cases from the previous month? For reference, I've included the NYT Github data below:
    https://github.com/nytimes/covid-19-...s-counties.csv

  • #2
    The following example may start you in a useful direction. Your actual data includes a geographic identifier named fips: this variable is needed to keep from subtracting the last month of a unit from the first month of the next unit's data, so I invented a value and added it to your example data. The most important thing is to convert your string date into a numeric Stata Internal Format monthly date, otherwise the date after 1-20 is 1-21.
    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input int fips str4 date int cases new_cases
    06555 "1-20" 0 0
    06555 "2-20" 1 1
    06555 "3-20" 3 2
    06555 "4-20" 5 2
    06555 "5-20" 7 2
    06555 "6-20" 9 2
    end
    format fips %05.0f
    // convert date to Stata Internal Format monthly date
    generate mdate = monthly(date,"M20Y")
    format %tm mdate
    bysort fips (mdate): generate wanted = cases - cases[_n-1]
    list, clean abbreviate(16)
    Code:
    . list, clean abbreviate(16)
    
            fips   date   cases   new_cases    mdate   wanted  
      1.   06555   1-20       0           0   2020m1        .  
      2.   06555   2-20       1           1   2020m2        1  
      3.   06555   3-20       3           2   2020m3        2  
      4.   06555   4-20       5           2   2020m4        2  
      5.   06555   5-20       7           2   2020m5        2  
      6.   06555   6-20       9           2   2020m6        2

    Comment

    Working...
    X