## Referring to vars in loops, mixing fixed and variable parts

Moderators: statman, Analyst Techy, andris, Fierce, GerineL, Smash

Tommy
Posts: 3
Joined: Tue Sep 04, 2012 9:37 am

### Referring to vars in loops, mixing fixed and variable parts

Hey all,

Hope someone can help me or point me into the right direction with this:

I'm trying to convert a syntax I wrote for Stata into SPSS and I can't find an easy solution to convert loops similar to the following Stata-code:

Code: Select all

``````foreach var in a b c {
gen `var'_vrnc= `var'_sd^2
}``````
How can I do this in SPSS? I tried it using LOOP, DO REPEAT and vectors, but it never worked as I thought it should.
My main problem seems to be how to refer to variable names that consist of a fixed part and a variable part that is changed over the loop.

Regards,
Tommy
Penguin_Knight
Posts: 473
Joined: Thu Apr 05, 2012 5:58 pm

### Re: Referring to vars in loops, mixing fixed and variable pa

What does that formula do? Is it just renaming a_vrnc to a_sd after squaring?
Tommy
Posts: 3
Joined: Tue Sep 04, 2012 9:37 am

### Re: Referring to vars in loops, mixing fixed and variable pa

Yes - to be exact, it squares "var"_sd and generates a new variable "var"_vrnc.

It should just serve as an example for the combination of "fixed" and "variable" parts of variable names in loops - that's what I want to get done in SPSS syntax.
Penguin_Knight
Posts: 473
Joined: Thu Apr 05, 2012 5:58 pm

### Re: Referring to vars in loops, mixing fixed and variable pa

Well... I personally prefer macro, but I bet there must be other ways of doing it:

Code: Select all

``````DEFINE MyMacro (MyVar = !ENCLOSE("[","]")) .
!DO !I !IN (!MyVar)
COMPUTE !CONCAT(!I, "_vrnc") = !CONCAT(!I, "_sd")**2 .
!DOEND
!ENDDEFINE .``````
Then, use this to evoke the macro. Put all your variables in between the [ and ]:

Code: Select all

``````MyMacro MyVar = [a b c] .
EXECUTE .
``````
Tommy
Posts: 3
Joined: Tue Sep 04, 2012 9:37 am

### Re: Referring to vars in loops, mixing fixed and variable pa

It works great, thank you very much!

I can't describe how useful this will be. Have to try that out with nesting multiple loops, but I think I will work it out from here. Maybe I'll post again if I encounter more specific problems.

Again, thank you

### Who is online

Users browsing this forum: No registered users and 1 guest