Announcement

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

  • Creating repeating sequential variable

    Fairly new to stata (and stats in general).

    I have a database I'm trying to analyze where each unique study ID has multiple entries in sequential rows, before the next study id. These rows are not numbered. I'm trying to figure out how to create a sequentially increasing variable that resets with each new unique study id. In other words, I want to create a variable for the first entry for studyid 1 to be 1, then the next entry for studyid 1 to be 2, the third entry for studyid 3 will be 3, etc. When studyid 2 comes up, I want the variable to reset to 1 then start climbing again until studyid 3, at which time it will reset to 1 again.

    What I'm ultimately trying to do is create a j-variable I can use to reshape the database with a bunch of entries for each study id to a wide form so I can add a bunch of outcomes variables that were previously put into a different database where each study id just has one column.

    Thanks for the advice. Sorry if this has been answered previously elsewhere, new to the forum...

  • #2
    If you want to do it so that the order j = 1, j = 2, j = 3,... is the current order of the observations in the data set, it's:

    Code:
    gen long obs_no = _n
    by study_id (obs_no), sort: gen j = _n
    drop obs_no
    If you don't care whether the j = 1, j = 2, j = 3 gives you the same order as the original, then it's just

    Code:
    by study_id, sort: gen j = _n
    Do read the Getting Started [GS] and User's Guide [U] sections of the online Stata manuals to familiarize yourself with all of the basic commands. Pay particular attention to the -by:- prefix and how _n and _N work with it. This reading will introduce you to the basic, bread and butter commands that are the foundations of data management and simple analysis in Stata. You won't be able to remember everything you read, but you will come away with a sense of what commands are available to you, so you can then refer back to the manuals or the on-line -help- files to remind yourself of the details. The short amount of time you need to go through these materials will be repaid rapidly.

    Finally, it is the norm in this community, to maintain professionalism and collegiality, that we use our real first and last names as our username. You cannot, unfortunately, change your username by editing your profile. But you can click on "CONTACT US" in the lower right to send a message to the Forum administrator requesting the change. Thank you.

    Comment

    Working...
    X