Announcement

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

  • Addition of 1 to multiple variables.

    Hello, I have 22 variables that I am trying to add 1 to. I am generating a new variable for each. For example,

    ​​​​​​capt drop dd1_knowledge_rc
    gen dd1_knowledge_rc = dd1_knowledge + 1 if dd1_knowledge !=.

    capt drop dd2_causes_rc
    gen dd2_causes_rc = dd2_causes + 1 if dd2_causes !=.

    I have tried without success:

    . foreach var of varlist dd1_knowledge dd2_causes dd3_physical dd4_psych ///
    > dd5_riskfactors dd6_counsel dd7_advise dd8_questrights dd9_askinfo dd10_persondiff ///
    > dd11_personrespon dd12_approach dd13_littlecando_rev dd14_workwell ///
    > dd15_failure_rev dd16_respect_rev dd17_uncomfort_rev ///
    > dd17_uncomfort dd18_satisfy dd19_reward dd20_iunderstand {
    2. gen`var'*_rc = + 1 if dd1_knowledge - dd20_iunderstand ! = .
    3. }


    I would sure appreciate an easier and efficient way!

    Thanks.

  • #2
    2. gen`var'*_rc = + 1 if dd1_knowledge - dd20_iunderstand ! = .
    3. }
    I don't know why you are trying to change how you formulate your command in the loop. Remember, a loop is simply an iteration of a command, so there is nothing special about it. So if you have the command

    Code:
    gen dd2_causes_rc = dd2_causes + 1 if dd2_causes !=.
    the loop should be defined as

    Code:
    gen `var'_rc = `var' + 1 if `var' !=.

    Comment


    • #3
      What Andrew said exactly--loop is just a repetition, so you repeat the command making it conditional on the macro.

      More explicitly, you replace what is in the curly brackets by

      Code:
      {
      capt drop `var'_rc
      gen `var'_rc = `var' + 1 if !missing(`var')
      }

      Comment


      • #4
        Very helpful. Thank you

        Comment


        • #5
          Not disagreeing; but note that adding 1 to missing just leaves missing, so trapping that doesn't save a problem. It's the same result either way.

          Comment


          • #6
            Given the code in post #1, Nick is correct in noting that checking for the system missing value is unnecessary.

            However, adding 1 to an extended missing value .a through .z results in the system missing value . which is why - since I use extended missing values extensively - I always use missing(x) to check for missing values and I qualify replace commands with a check for missing, and rather than generate I typically do
            Code:
            clone xnew = x
            replace xnew = x+1 if !missing(x)
            which (a) copies and preserves system missing values and (b) copies any format or label associated with x to xnew, for better or worse.

            Comment

            Working...
            X