Announcement

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

  • New variable creation loop

    Hi everyone! I am having some trouble creating new variables. My goal is for the name of the variable to be looped. To be precise, I want to create as many variables as the max value of another variable called cal_year_duration, and then the name of the new variable should be Y1 if year_duration =1, Y2 if year_duration=2. My code to this point looks like this and there is a sample of data below, but I'm pretty sure I am doing something wrong so any help would be greatly appreciated. Thanks in advance!

    forvalues i=1 & i<=max(cal_year_duration) {
    gen Y`i'= .
    }

    . dataex cal_year_duration
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float cal_year_duration
    1
    2
    5
    15
    3
    4
    2
    7
    8
    1
    end

  • #2
    you can use levelsof to cycle through the distinct values of cal_year_duration,
    Code:
    levelsof cal_year, local(levels)
    foreach l of local levels {
    gen Y`l'=.
    }

    Comment


    • #3
      That worked, thank you!

      Comment


      • #4
        Maybe this is what you looking for:

        Code:
        su cal_year_duration
        local max_duration = r(max)
        
        forvalues i = 1/`max_duration'{
            gen Y`i' = cal_year_duration if cal_year_duration == `i'
            }

        Comment


        • #5
          Code:
          separate cal_year_duration, by(cal_year_duration)
          does the loop for you.

          Note that the forms allowed with forvalues are documented, and nothing else will work.

          Comment

          Working...
          X