Announcement

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

  • Regression loop where dependent and independent variables change based on value from another variable

    I want to run a regression where the dependent variable is based on the group specified by one variable and the independent variables are all other variables apart from that. Here is an example dataset:

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input byte(var1 var2 var3 var4 group)
    22 45 66 87 4
    45  3 33 44 2
    12  2  5 35 1
    34 66  2 11 3
     5 42  4  7 2
    32 56  7 44 3
    87  1 22  2 4
     6  3  1  9 1
    45 45 45 87 2
     3 12  3 44 1
     2 34  2 33 3
    66  5 44  5 3
    42 32  2  2 4
    56 87  9  4 2
     1  4  5  7 1
     3  7 32 22 3
    end
    I figured out how to make the dependent variable:
    Code:
    gen dep_var=.
    forval j=1/4{
        replace dep_var = var`j' if group==`j'
    }
    How can I make a loop that runs a regression of dep_var against all remaining variables? For instance, in the first observation row, it regresses dep_var against var_1, var_2 and var_3 but in the second row, it regresses dep_var against var_1, var_3 and var_4, and so on. In my actual dataset, I have 20 groups and want to run combination of different regressions based on group type.
    Last edited by Chirag Yadav; 03 Dec 2024, 19:28.

  • #2
    This can't be run in your example data because most of the four groups instantiated have too few observations to support three right hand side variables. But in the full data set:
    Code:
    local allvars var1 var2 var3 var4
    
    forvalues j = 1/4 {
        local dv: word `j' of `allvars'
        local ivs: list allvars - dv
        regress `dv' `ivs' if group == `j'
    }
    Added: By the way, this code does not require your variables to actually be named var1, var2, var3, and var4. It will accept any four actual variable names in your data set. You just have to list them in the correct order in local macro allvars.

    Comment


    • #3
      Thanks! I had never seen the "word" command before. This is awesome.

      Comment

      Working...
      X