Announcement

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

  • Increasing value of a variable (and subsequent values of the variable) by 1

    Hi,

    I think this will be relatively straight forward to anyone who has more experience with Stata than me - which is probably most of you on here.

    I am trying to increase the value of a variable 'visit' by +1, but also require the subsequent values of 'visit' for that particular id to increase by +1 as well.

    Here's my example data:

    id visit dup datesubmitted
    01 1 1 10dec2015
    01 1 2 10apr2016
    01 2 1 11aug2016
    01 3 1 21dec2016
    01 4 1 14apr2017
    01 5 1 15aug2017

    In the above example I am trying to get the second visit 1 in which dup == 2 and datesubmitted is 10apr2016 to take on the value of 2, and then all the subsequent visits to increase by 1.

    i.e what i would like to happen is this:
    .:
    id visit dup datesubmitted
    01 1 1 10dec2015
    01 2 2 10apr2016
    01 3 1 11aug2016
    01 4 1 21dec2016
    01 5 1 14apr2017
    01 6 1 15aug2017


    But when I use the command
    by studyid: replace visit = visit[_n+1] if dup==2

    this only increases 'visit' by 1 when dup==2 (as expected) but i can't work out the code to increase the subsequent visit numbers.

    Any ideas would be really appreciated.

    Thanks,

    Janey

  • #2
    If I'm understanding it correctly, you don't need that variable dup. You just want to renumber the visits in chronological order, right? If so:

    Code:
    by  studyid (datesubmitted), sort: replace visit = _n

    Comment


    • #3
      Thanks, unfortunately it isn't a case of renumbering the visits in chronological order as i have other id's that have been allocated visit numbers that i don't want to be renumbered (and aren't necessarily in chronological order). The difference is that those id's (that i don't want renumbered) don't have dup value of 2, only 1.
      I created the dup variable to count the observations in which visits were assigned the same visit number, now that they are identified i want to replace the repeated visit with n+1 and then all the subsequent visits with n+1.

      Hope that makes sense.

      Comment


      • #4
        Janey: You can try Clyde's code safely by creating a new variable

        Code:
        egen ever2  = max(dup == 2), by(id)  
        by  studyid (datesubmitted), sort: gen VISIT = _n if ever2

        Comment


        • #5
          Great, thanks so much Clyde and Nick.

          Comment

          Working...
          X