Announcement

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

  • Loop going through distinct values of variable1 and replacing distinct string in variable2 per each iteration

    Hi all,

    I have this kind of reproducible code:
    Code:
    clear
    
    set obs 10
    gen str names = ""
    gen num = _n
    
    su num, meanonly
    di `r(max)'
    
    local abc a b c d e f g h i l
    forval i = 1/`r(max)' {
        foreach x of local abc {
            replace names=`"`x'"' if num == `i'
            }
        }
    What I would expect is for it to produce a column with "a, b, c, d,...". Instead, I get a column full of "L".
    I also checked Statalist but could not figure out why the code is not working.

    I'm sure it's a silly mistake, but I find myself stuck.

    Thank you

  • #2
    It is really one loop going over two lists in parallel. By writing two (nested) loops, you are answering, at best, a different question,

    See some ancient discussion in https://www.stata-journal.com/articl...article=pr0009

    Here is a way to do that I like (noting in passing that in your example you don't need a loop at all). Also, in this case in would be better than if,

    Code:
    clear
    
    set obs 10
    gen str names = ""
    gen num = _n
    
    su num, meanonly
    di `r(max)'
    
    local abc a b c d e f g h i l
    
    gen wanted = word("`abc'", _n)
    
    quietly forval i = 1/`r(max)' {
        gettoken this abc : abc
        replace names=`"`this'"' if num == `i'
    }
    
    list
    
         +----------------------+
         | names   num   wanted |
         |----------------------|
      1. |     a     1        a |
      2. |     b     2        b |
      3. |     c     3        c |
      4. |     d     4        d |
      5. |     e     5        e |
         |----------------------|
      6. |     f     6        f |
      7. |     g     7        g |
      8. |     h     8        h |
      9. |     i     9        i |
     10. |     l    10        l |
         +----------------------+
    Last edited by Nick Cox; 22 Aug 2019, 03:13.

    Comment


    • #3
      Thank you Nick, this is very informative. Notice also how I indented consistently this time. Your words are not wasted on me.

      Comment

      Working...
      X