Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: st: loop with egen
From
Nick Cox <[email protected]>
To
[email protected]
Subject
Re: st: loop with egen
Date
Fri, 8 Feb 2013 14:00:47 +0000
If that's true, then
foreach v of var <varlist> {
qui su `v'
gen mean_`v' = r(mean)
gen sd_`v' = r(sd)
}
is a more efficient way of doing it. -egen- has lots of stuff that is
irrelevant for your purpose.
I've found that for occasional graphics tricks it is helpful to put
variables into constants. Otherwise I think my "usually" is still
true.
On Fri, Feb 8, 2013 at 1:51 PM, Nahla Betelmal <[email protected]> wrote:
> Dear all
>
> many thanks Rich, and yes I had the variables in my command already.
> this was not the problem. The issue was with each variable new name.
>
> Thanks Nick, the loop works perfectly. I need to generate the
> constants as variables to use in further equations and calculations
> instead of writing them manually.
>
> Many thanks again
>
> Nahla
>
>
> On 8 February 2013 13:38, Nick Cox <[email protected]> wrote:
>> I don't believe that was your code.
>>
>> I suspect that you wrote something of the form
>>
>> foreach v of var <varlist> {
>> egen mean = mean(`v')
>> egen sd = sd(`v')
>> }
>>
>> where instead of <varlist> you had a list of variable names.
>>
>> Second time around the loop, the problem is that -mean- already
>> exists, and so the loop fails.
>>
>> You could make this loop legal by ensuring that each new variable has
>> a different name
>>
>> foreach v of var <varlist> {
>> egen mean_`v' = mean(`v')
>> egen sd_`v' = sd(`v')
>> }
>>
>> but that would still be a bad idea. There is usually little point in
>> generating lots of variables that just contain constants.
>>
>> su <varlist> will give you a list of means and standard deviations.
>>
>> For more precise control, consider
>>
>> . sysuse auto
>> (1978 Automobile Data)
>>
>> . tabstat mpg weight, s(mean sd) c(s) format(%2.1f)
>>
>> variable | mean sd
>> -------------+--------------------
>> mpg | 21.3 5.8
>> weight | 3019.5 777.2
>> ----------------------------------
>>
>> Nick
>>
>> On Fri, Feb 8, 2013 at 1:29 PM, Nahla Betelmal <[email protected]> wrote:
>>
>>> I am trying to generate the mean and standard deviation for more than
>>> 30 variables. I tried to do that using the following loop
>>>
>>> foreach v of var {
>>> egen mean = mean(`v')
>>> egen sd = sd(`v')
>>> }
>>>
>>> however, it only generate the mean and standard deviation for the
>>> first variable only.
>>>
>>> I got this message :mean already defined
>>> r(110);
>>>
>>> what should I add to the loop , so it can generate the mean and
>>> standard deviation for each variable in separate column?
*
* For searches and help try:
* http://www.stata.com/help.cgi?search
* http://www.stata.com/support/faqs/resources/statalist-faq/
* http://www.ats.ucla.edu/stat/stata/