Announcement

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

  • Return maximum values for a set of combinations

    I want to return the highest number from a column for a specific country in a specific month and a specific year. I have 255 countries, 12 months and 3years. The code below was what I used but it kept giving me this error - "variable max_cases already defined". I checked over many times and I can't seem to find the solution. Can anyone help please? Thank you.

    gen maxcases = .

    // Get the unique values of the country variable
    levelsof iso_code, local(country_list)

    // Loop through different combinations of countries, months, and years
    foreach country in `country_list' {
    foreach month in 1/12 {
    foreach year in 1 2 3 {
    // Calculate the maximum number of cases for the current combination
    egen max_cases = max(cases) if iso_code == "`country'" & month_id == `month' & year_id == `year'

    // Update the maxcases variable with the maximum number of cases
    replace max_cases = maxcases if iso_code == "`country'" & month_id == `month' & year_id == `year'
    }
    }
    }

  • #2
    You create the variable max_cases the first time through the loop. When you come back the second time, it already exists, so you cannot -egen- it again.

    But there is no reason to do this with any loops.

    Code:
    by iso_code month_id year_id, sort: egen max_cases = max(cases)
    is all you need.

    Comment

    Working...
    X