Announcement

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

  • Looping over numbers in local

    Hey,

    I want to loop over numbers of a list (in a local). The code looks like the following:

    local lambdas 400000 100000 25000 1600

    foreach lambda in local lambdas {
    foreach x in b t {
    [INDENT=2]gen test_`x'_`lambda' = .[/INDENT]
    }
    }
    The code creates the (wrong) variables:
    test_b_local
    test_t_local
    test_b_lambdas
    test_t_lambdas

    Where is my mistake? In a similar situation I use --levelsof-- in order to get the levels of a specific variable and safe them in a local. I also want to loop over them. Same problem.

    Thanks in advance!

  • #2
    It is

    Code:
    foreach lmacname of local lmacname {
    ...
    Best
    Daniel

    Comment


    • #3
      Thanks, but that's not what the documentation says (e.g. Method 2 of http://www.stata.com/support/faqs/da...-with-foreach/). Furthermore it seems to work if I use `lambdas' instead of local lambdas.

      I'm currently just a bit confused because sometimes it works, sometimes it doesn't.

      Comment


      • #4
        Pay attention to the difference between -foreach lmacname of ...- and -foreach lmacname in ...-. They work differently, but each one works as described in the documentation. The -of- and -in- are not interchangeable: they do different things.

        Comment


        • #5
          Oh, you're right, sorry! Thanks for the hint!

          The devil obviously was in the details...

          Comment


          • #6
            But the site you cite does exactly say what I have said.

            Code:
            foreach l of local levels {
            ...
            Note that it is not "the documentation", though. The latter is found typing

            Code:
            help foreach
            and does explain how the command works.

            Edit:

            It appears emphasis using bold characters is not the best when used in code delimiters. Thanks to Clyde for just verbalizing the crucial point.

            Best
            Daniel
            Last edited by daniel klein; 05 Jul 2017, 12:53.

            Comment


            • #7
              Yes, I didn't see the "of". Bold character don't really work in code delimiters (only if you look closely).

              I didn't know how to call it instead of "documentation". I thought it should at least come close.

              Well, problem is solved, thanks to both of you for your help!

              Comment

              Working...
              X