Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.

# Re: st: creating a foreach loop for principal components

 From Nick Cox To statalist@hsphsun2.harvard.edu Subject Re: st: creating a foreach loop for principal components Date Sun, 4 Sep 2011 09:30:23 +0100

```      local this : list all - `j'

On Fri, Sep 2, 2011 at 7:20 PM, Nick Cox <njcoxstata@gmail.com> wrote:
> examples are entirely in terms of omitting variables. I am going to
> assume you mean the latter.
>
> NB: Observations are rows; variables are columns. BTW, -pca- is a
> command, not a function.
>
> The structure you seem to be asking for can be coded like this.
>
> unab all : var1-var300
> tokenize `all'
>
> forval j = 1/300 {
>      local this : list all - ``j''
>      pca `this'
>      predict pc1-pc5
>      regress ``j'' pc1-pc5
>     drop pc1-pc5
> }
>
> Nick
>
>
> On Fri, Sep 2, 2011 at 7:09 PM, Dmitriy Glumov <glumovdm@gmail.com> wrote:
>
>> I am working on principal components and have run into a problem
>> creating a loop. I have about 300 observations and each one needs to
>> undergo a 3 step process: 1) Creating principal components WITHOUT the
>> respective observation (principal components function itself is very
>> simple, but I struggle to create a loop for it), 2) Predicting first 5
>> components (this step doesn't change, but component values themselves
>> are dependent on step 1), and 3) Regressing the respective variable
>> onto the components.
>>
>> To illustrate, the process for variable 1 would look something like this:
>> pca var2-var300
>> predict pc1-pc5
>> regress var1 pc1-pc5
>>
>> For variable 2, it would be this:
>>
>> pca var1 var3-var300
>> predict pc1-pc5
>> regress var2 pc1-pc5
>>
>> For variable 3,
>>
>> pca var1-var2 var4-var300
>> predict pc1-pc5
>> regress var3 pc1-pc5
>>
>> and, so on for the remaining variables. It is certainly doable by
>> hand, but the process is very time-consuming. I am sure there is a way
>> to create a foreach loop but I just can't figure out how. So if you
>> can help me with this, it would be greatly appreciated. Thank you for