Announcement

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

  • Renaming variables in loop

    Hello all,

    I'm working with a dataset which has variables with counters as follows: payment_1, payment_2, payment_3, etc. I want to loop over each of these variables and use `encode' as in the code below. However, when naming the new variable, I want to keep a common suffix with 1,2,3...added in the end. More precisely, I want to the new variable names to look like pe_1, pe_2, pe_3, etc. Is there a way to do this in the same line of code, Apologies if my question is not clear. And thanks for any suggestions!
    Code:
     foreach `var' of varlist payment_* {
        encode `var', gen(`newname')
    }
    Last edited by Mansha Mahajan; 14 Mar 2022, 17:11.

  • #2
    Code:
    foreach var of varlist payment_* {
        local newname: subinstr local var "payment" "pe"
        encode `var', gen(`newname')
    }
    Note that there are no macro quotes around var in the -foreach- command, nor in the -local newname- command, although they must be present in the -encode- command

    Comment


    • #3
      This is perfect! Thanks so much Clyde.

      Comment


      • #4
        A different issue is that you (presumably) want to use the same encoding for your variables. multencode from SSC will ensure this; separate encoding won't produce it automatically..

        Comment

        Working...
        X