Announcement

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

  • How could I have done this better?

    Hi

    I have a two panel data set with a ordered response variable in it, call it "Pain". Pain takes values 1-5, with 1 being a lighter level of pain. I'd like a to generate a variable that is -1 for a positive change in in Pain, 0 for no change and 1 for negative change. Below is what I did that eventually worked. I'd like to know a better way as one must exist.

    gen chng = pain- L.pain if !missing(pain)

    generate hidy = 1 if chng < 0 & !missing(chng)

    replace hidy = -1 if chng >0 & !missing(chng)

    replace hidy = 0 if chng == 0 & !missing(chng)

    I leaving out all the tabulations i did to make sure it was right.

    There has to be a better way to do this. I know its whiny but I'd like to learn the language better.

  • #2
    "better" is not clearly defined, but it can certainly be done in one command:

    gen chg=cond(pain>pain[_n-1],-1,cond(pain<pain[_n-1],1,cond(pain==pain[_n-1],0,cond(pain==.,
    > .,.))))

    I think that this does what you want, but ...

    Comment


    • #3
      well, what I just wrote ignore the fact of the panel structure, but you probably get the basic idea anyway

      Comment


      • #4
        You could have used a recode command right after the first gen command. Only one line and maybe less error prone.
        -------------------------------------------
        Richard Williams, Notre Dame Dept of Sociology
        StataNow Version: 18.5 MP (2 processor)

        EMAIL: [email protected]
        WWW: https://www3.nd.edu/~rwilliam

        Comment


        • #5
          Perhaps you could avoid creating the variable chng (unless you really need that variable) and writing your code in just two commands. You can also make advantage of the operator D.varname
          Here is a simple example:
          Code:
          webuse xtsetxmpl
          xtset pid tod, clocktime delta(1 hour)
          gen hidy=(D.y<0) & !missing(D.y)
          replace hidy = -1 if D.y >0 & !missing(D.y)
          If you want, you can check your results (a simple tab hidy may fit that purpose).

          Hope this helps.
          Carlos

          Comment


          • #6
            I go one step beyond Carlos and make it

            Code:
            gen hidy = -sign(D.pain)
            The missings come automatically if the first differences are missing. Kevin wants -1 if something is increasing and 1 if it is decreasing and 0 if it is unchanged. Assuming that pain means pain, less pain would mean, indeed less pain, and so sounds good. So it is the negation of the signum of the first difference, and respect for panel structure comes with the difference operator.

            Comment

            Working...
            X