Announcement

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

  • Forvalues command for specific value of another variable

    Dear Statalist Members,

    Consider a city-time panel. There are 81 cities, each has a unique identifier called variable "plate" from 1 to 81. The years span from 2003 to 2018. Each city is observed once from 2003 to 2018.

    I'd like to create a variable, let's say "constant". I want this "constant" variable to take 10 (because another variable, let's call it "X" is 10 in year 2017) for city A (the city is A has unique identifier called "plate" which is 1) across all years from 2003 to 2018. I would like "constant" variable to take 10 across all years from 2003 to 2018 for city A.

    For example, if this X variable is 15 in 2017 for city B (which has a unique identifier plate==2), I want this "constant" variable to take 15 from 2003 to 2018 for city B.

    I have used forvalues command but I cannot make it.

    I would be reallt appreciated if you can help me.

    Best,
    C

  • #2
    Code:
    by plate, sort: egen wanted = max(cond(year == 2017, X, .))
    In the future, when asking for help with code, it is more helpful to show example data than to attempt to describe a data set. The best way to show example data is by using the -dataex- command. If you are running version 18, 17, 16 or a fully updated version 15.1 or 14.2, -dataex- is already part of your official Stata installation. If not, run -ssc install dataex- to get it. Either way, run -help dataex- to read the simple instructions for using it. -dataex- will save you time; it is easier and quicker than typing out tables. It includes complete information about aspects of the data that are often critical to answering your question but cannot be seen from tabular displays or screenshots. It also makes it possible for those who want to help you to create a faithful representation of your example to try out their code, which in turn makes it more likely that their answer will actually work in your data.

    Comment


    • #3
      Code:
      bysort plate: egen wanted= max(cond(year==2017, X, .))
      https://journals.sagepub.com/doi/pdf...867X1101100210 for a review of technique.

      Note: Crossed with #2.

      Comment

      Working...
      X