Announcement

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

  • Efficient Way to Reform Repeated Codes with IF condition

    Dear experts,

    For the following repeated codes :


    tab1 variable1 if (variableA == 1) & (variableB== 1), missing
    tab1 variable1 if (variableA == 1) & (variableB== 1) & (variableC== 1), missing
    tab1 variable1 if (variableA == 1) & (variableB== 1) & (variableD== “no reason”), missing

    tab1 variable2 if (variableA == 1) & (variableB== 1), missing
    tab1 variable2 if (variableA == 1) & (variableB== 1) & (variableC== 1), missing
    tab1 variable2 if (variableA == 1) & (variableB== 1) & (variableD== “no reason”), missing

    tab1 variable3 if (variableA == 1) & (variableB== 1), missing
    tab1 variable3 if (variableA == 1) & (variableB== 1) & (variableC== 1), missing
    tab1 variable3 if (variableA == 1) & (variableB== 1) & (variableD== “no reason”), missing

    …….
    …….
    If I repeat doing the same above for variable1, variable2, variable3……variable6

    Other than using macro below, is there any more efficient way? e.g. using loop?
    Thank you for help.


    local repeat variable1 variable2 variable3 variable4 variable5 variable6
    tab1 `repeat’ if (variableA == 1) & (variableB== 1), missing
    tab1 `repeat’ if (variableA == 1) & (variableB== 1) & (variableC== 1), missing
    tab1 `repeat’ if (variableA == 1) & (variableB== 1) & (variableD== “no reason”), missing

  • #2
    first, note that your local is not doing what you think it is and I would expect -tab1- to give an error message; you have set the local "repeat" to be a set of variables and tab1 will attempt to use all at once; try this instead:
    Code:
    forval i=1/6 {
      tab1 variable`i’ if (variableA == 1) & (variableB== 1), missing
      tab1 variable`i’ if (variableA == 1) & (variableB== 1) & (variableC== 1), missing
      tab1 variable`i’ if (variableA == 1) & (variableB== 1) & (variableD== “no reason”), missing
    }

    Comment


    • #3
      Thank you for your replying.
      tab 1 is working well when I executed the macro.

      Also, variable1-variable6 have their variable names. For example,

      local repeat gender race
      tab1 `repeat’ if (variableA == 1) & (variableB== 1), missing
      tab1 `repeat’ if (variableA == 1) & (variableB== 1) & (variableC== 1), missing
      tab1 `repeat’ if (variableA == 1) & (variableB== 1) & (variableD== “no reason”), missing


      So I am not using variabe `i'
      May I apply any loop?
      Last edited by Anthony Jones; 14 Nov 2019, 19:30.

      Comment


      • #4
        yes, sorry, I forgot that tab1 allows a varlist

        I don't understand what you are now asking

        Comment

        Working...
        X