-1

I am starting with a list of variables that I would like to run regressions on. I would then like to save their coefficients as a scalar with a number on the end. For example, here is my code so far

local varlist="vertical reps"        
foreach variable of local varlist{
forval i=1/2{
quietly reg successorfail `variable'
scalar s`i'=_b[`variable']
}
}

When I list the results of this I just get:

s2 =  .00928925
s1 =  .00928925

So it is creating new scalars with just the last regression coefficient it ran.

I would like the result to be:

s1=first reg coefficient
s2=2nd reg coefficient

Thanks!

Pcarlitz
  • 223
  • 1
  • 5
  • 17

2 Answers2

2

This works:

clear all
set more off

sysuse auto

local varlist mpg weight
local i 0

foreach variable of local varlist {
        local ++i 
        quietly reg price `variable'
        scalar s`i'=_b[`variable']
        display s`i'
}

A couple of things with your code:

  1. There's no need for the second loop. You can use a local as a counter if you want to append the loop number to the scalar name. I use the local i and update it (i.e. add 1 to it) with each pass through the loop. More importantly, note that for each independent variable, you are running the same regression twice (because of the forval i=1/2).

  2. I can't see what you're trying with the line local varlist = "vertical reps". The regressors you should define outside the loop, if that's what you're aiming at.

Roberto Ferrer
  • 11,024
  • 1
  • 21
  • 23
  • excellent. I didn't know stata had a local counter like that. I was simply creating a local macro of my variables with the local varlist command just like you did in your example. THANK YOU – Pcarlitz Feb 10 '14 at 20:35
2

For reference, here is another way to do it.

clear all
set more off

sysuse auto

local varlist "mpg weight"
local nv : word count `varlist' 
tokenize "`varlist'" 

forval i = 1/`nv' {
    quietly reg price ``i''
    scalar s`i'=_b[``i'']
    display s`i'
}
Nick Cox
  • 35,529
  • 6
  • 31
  • 47
  • Thanks for this. I did some research on the "tokenize" command and this is a smart way of going about it. – Pcarlitz Feb 10 '14 at 21:27