Automating the creation of randomly split-out text files with an SPSS macro

SPSS macro

I frequently need to randomize my lists and save them into separate text files. This SPSS macro makes it a breeze!

If you haven’t already played with macros you’ll want to get yourself familiar with them by reviewing this post on Intro to Macros. ┬áThe macro will need a few parameters from you like: the path to save the files, Stem (beginning) name of the files to create, # of groups to create and whether or not to keep the variable used to create the groups.

Below is the SPSS Macro which will automate the process.

 
*/////////////////////.
DEFINE !Rand_Gp_txt (Path !Tokens(1)/Stem !Tokens (1)/Groups !TOKENS (1)  /DropNewVars !Tokens(1))
*/////drop GP if already exists . 
Match files file=* / DROP Temp_GP 
Compute Rand=RV.UNIFORM(0,1).
RANK  VARIABLES=rand (A) /NTILES (!Groups) into Temp_GP /PRINT=Yes /TIES=HIGH.
Freq Temp_GP.
***********************break out and save in groups********************************.
!DO !cnt=1 !TO !Groups.
Temp.
Select if Temp_GP=!cnt.
SAVE TRANSLATE OUTFILE = !Path+!stem+!QUOTE(!CONCAT(!cnt,'.txt'))
  /TYPE=TAB /FIELDNAMES /replace /KEEP= ALL  /drop=Temp_GP rand.
!DOEND

***Drop unwanted vars if *******.
!IF (!Unquote(!Upcase(!DropNewVars))="Y") !THEN  
	Match files file=* / DROP Rand Temp_GP. 
!IFEND

!ENDDEFINE.
*/////////////////////.
!Rand_Gp_txt Path="c:\temp\" Stem="Rand_" Groups=2  DropNewVars="Y".
Remember to define the SPSS macro before calling it!.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.