Announcement

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

  • Creating a loop to generate variables using common names

    I need to generate 24 variables and I'm wondering if there is a way to create a loop that will make it faster and save 48 lines of code. They have the same naming structures, but I'm not sure that's enough to create a loop. I have 21 more variables, all with the same naming structure, to code.

    Code:
    gen acc_star = "*" if acccnt<7
    replace acc_star = acc_rank if acccnt>=7
    gen fin_star = "*" if fincnt<7
    replace fin_star = fin_rank if fincnt>=7
    gen rest_star = "*" if restcnt<7
    replace rest_star = rest_rank if restcnt>=7

  • #2
    Try

    Code:
    foreach stub in acc fin rest ... {
        generate `stub'_star = cond(`stub'cnt < 7, "*", `stub'_rank)
    }
    Best
    Daniel

    Comment


    • #3
      perhaps something like this:
      Code:
      foreach i in acc fin rest {
         gen `i'_star = "*" if `i'cnt<7
        replace `i'_star = `i'_rank if `i'cnt>=7
      }

      Comment

      Working...
      X