Re: Help with macros
Posted by Kirill Orlov on
URL: http://spssx-discussion.165.s1.nabble.com/Help-with-macros-tp5740865p5740881.html
Eleonora,
The suggestion made by Bruce (the suggestion to loop through the list of names via macro !DO ... !IN(...)) is probably what will suit you. But it implies that the list of the input variable names is a complete name-by-name list, such as var1 var2 var3 var4.
Below is a recipe which allows to input variable name list also in a short form, such as var1 TO var4.
The macro below does the counting of variables by COUNT command - exactly like you did it in your macro in the question. The solution uses then WRITE command to prepare the DO REPEAT of the main job.
define !macro(vars= !cmdend)
!let !prefix= 'NEW_'
/*Auxiliary actions.
*(please replace below the path D:\EXERCISE\ with some one where you can save files to on your PC).
string nvars##$ (a8).
do if $casenum=1. /*Just for one case, do the following
count nvars###= !vars (MISSING LO THRU HI). /*Count the number of variables
compute nvars##$= ltrim(string(nvars###,f8)). /*nvars### in string format
write outfile= 'D:\EXERCISE\my temporary file.sps'
/'do repeat x= ' !quote(!vars)
/' /y= ' !quote(!prefix) '1 to ' !quote(!prefix) nvars##$ '.'.
end if.
execute. /*Run the transformation action
*The main task of your macro.
insert file= 'D:\EXERCISE\my temporary file.sps'. /*Read the DO REPEAT command
compute y= rnd(uniform(x)). /*Some your computations
/*(in this example: generate a random integer between 0 and X)
end repeat. /*Close the END REPEAT
execute. /*Run the transformation action
/*You may want to remove traces of your auxiliary actions.
*delete variables nvars### nvars##$.
*erase file 'D:\EXERCISE\my temporary file.sps'.
!enddefine.
*EXAMPLE.
data list list /var1 var2 var3.
begin data
1 4 1
3 8 5
2 6 4
0 2 9
end data.
dataset name data.
*Run your macro.
!macro vars= var1 var2 var3.
*You can also run.
!macro vars= var1 to var3.
*-----------------------.
Your 'my temporary file.sps' syntax file contained this.
do repeat x= var1 var2 var3
/y= NEW_1 to NEW_3 .
If the list of variables vars can be long, a more relible way to write out the DO REPEAT will be:
write outfile= 'D:\EXERCISE\my temporary file.sps'
/'do repeat x= '
!do !w !in (!vars)
/' ' !quote(!w)
!doend
/' /y= ' !quote(!prefix) '1 to ' !quote(!prefix) nvars##$ '.'.
instead of the:
write outfile= 'D:\EXERCISE\my temporary file.sps'
/'do repeat x= ' !quote(!vars)
/' /y= ' !quote(!prefix) '1 to ' !quote(!prefix) nvars##$ '.'.
so each of your vars variables will occupy a separate line in 'my temporary file.sps' syntax file.