Announcement

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

  • counter in a loop

    Hi,

    I am running a loop in which I have a variable and 10 iterations. I want to set the variable name, starting with a number in each iteration, so that the variable's name be something like "1 x" in the first iteration, "2 x" in the second, and so on and so forth. I would appreciate any solution. Thanks,

  • #2
    Are you using a forvalues loop? In that case the counter is just the local macro created by the loop:

    Code:
    forval x = 1/10{
    gen `x'x = .
    }
    Otherwise, create a local macro before the loop and add one to it at the end of each iteration:

    Code:
    local x = 1
    foreach i of local ten_items{
    gen `x'x = .
    local ++x
    }

    Comment


    • #3
      Variable names cannot start with a number, and cannot have a space within them.

      Code:
      . clear
      
      . set obs 3
      number of observations (_N) was 0, now 3
      
      . gen 1x = 7
      1x invalid name
      r(198);
      
      . gen 1 x = 7
      1 invalid name
      r(198);

      Comment


      • #4
        Joro is right, of course -- simply use x`x' instead of `x'x in the code from #2.

        Comment

        Working...
        X