Announcement

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

  • gen variables

    Hi I have a variable named worry_30 taking values from 1 to 5.

    I want to gen 4 variables,


    worry_30_2 which take value 0 if worry_30 takes value 1 , otherwise worry_30_2 takes value 1


    worry_30_3 which take value 0 if worry_30 takes value 1 or 2 , otherwise worry_30_2 takes value 1


    worry_30_4 which take value 0 if worry_30 takes value 1 or 2 or 3, otherwise worry_30_4 takes value 1


    worry_30_5 which take value 0 if worry_30 takes value 1 or 2 or 3 or 4, otherwise worry_30_5 takes a value 1

    how I can do this please



    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float worry_30
    1
    1
    1
    5
    1
    3
    3
    1
    3
    1
    .
    3
    2
    1
    1
    1
    1
    3
    2
    4
    1
    1
    1
    4
    1
    3
    1
    1
    1
    5
    1
    1
    3
    2
    2
    1
    1
    1
    1
    1
    3
    5
    1
    4
    3
    1
    4
    2
    1
    3
    1
    2
    3
    3
    2
    2
    1
    1
    2
    2
    .
    2
    2
    1
    2
    1
    1
    1
    1
    2
    3
    1
    1
    4
    1
    1
    4
    3
    1
    2
    4
    1
    2
    5
    2
    3
    3
    2
    1
    2
    1
    3
    1
    1
    1
    1
    1
    2
    4
    2
    end
    [/CODE]

  • #2
    Hi

    I have generated the variables

    cap generate worry_30_2 = 0 if worry_30!= .
    cap replace worry_30_2 = 1 if worry_30>= 2



    cap generate worry_30_3 = 0 if worry_30!= .
    cap replace worry_30_3 = 1 if worry_30 >= 3




    cap generate worry_30_4 = 0 if worry_30!= .
    cap replace worry_30_4 = 1 if worry_30 >= 4



    cap generate worry_30_5 = 0 if worry_30!= .
    cap replace worry_30_5 = 1 if worry_30 >= 5


    but I want the variables worry_30_2 to worry_30_5 to take value .(missing) if the values in the worry is also missing . How I can edit the commands please

    Comment


    • #3
      Code:
      gen worry_30_2 = worry_30 > 1 if worry_30 < .

      Comment


      • #4
        Code:
        forvalues k = 2/5 {
            gen byte worry_30_`k' = worry_30 >= `k' if worry_30 < .
        }
        Incidentally, I would avoid using cap unless you really need it -- capture prevents your code from crashing in the event of a problem, which is a good thing when you are specifically telling Stata what to do in the event of a problem. In the absence of that, you can end up with your code crashing unexpectedly at other places, and it will be hard to troubleshoot the problem since you would have prevented Stata from giving you an error where the problem occurred.

        Comment

        Working...
        X