user3288190
user3288190

Reputation: 21

Conditional processing in SPSS

I would like to conditionally process blocks of syntax where the condition is based on the active data set.

Within an SPSS macro, you can conditionally process a block of syntax using the !IF/!IFEND macro command. However, as far as I can tell, the user is required to explicitly give a value to the flag by either using the !LET command (!LET !FLAG = 1), or by using a Macro input variable. This is wildly different from my experience with other languages, where I can write code that has branching logic based on the data I'm working with.

Say that there is a block of syntax that I only want to run if there are at least 2 records in the active data set. I can create a variable in the data set which is equal to the number of records using the AGGREGATE function, but I can't find a way to make a macro variable equal to that value in a way that is usable as a !IF condition. Below is a very simple version of what I'd like to do.

COMPUTE DUMMY=1.  

AGGREGATE  
 /OUTFILE = * MODE = ADDVARIABLES  
 /BREAK DUMMY  
 /NUMBER_OF_CASES = N.  

!LET !N_CASES = NUMBER_OF_CASES.  

!IF (!N_CASES > 1) !THEN  
 MEANS TABLES = VAR1 VAR2 VAR3.  
!IFEND

Is what I'm attempting possible? Thanks in advance for your time and consideration.

Upvotes: 2

Views: 733

Answers (1)

eli-k
eli-k

Reputation: 11310

Following is a way to put a value from the dataset into a macro, which you can then use wherever you need - including in another macro. First we'll make a little dataset to recreate your example:

data list free/var1 var2 var3.
begin data 
1 1 1 2 2 2 3 3 3 
end data.
* this will create the number of cases value:
AGGREGATE   /OUTFILE = * MODE = ADDVARIABLES   /BREAK  /NUMBER_OF_CASES = N.  

Now we can send the value into a macro - by writing a separate syntax file with the macro definition.

do if $casenum=1.
write out='SomePath\N_CASES.sps' /"define !N_CASES() ", NUMBER_OF_CASES, " !enddefine.".
end if.
exe.
insert file='SomePath\N_CASES.sps'.

The macro is now defined and you can use the value in calculations (e.g if you want to use it for analysis of a different dataset, or later in your syntax when the current data is not available).
for example:

compute just_checking= !N_CASES .

You can also use it in your macro as in your example - you'll see that the new macro can't read the !N_CASES macro as is, that's why you need the !eval() function:

define !cond_means ()
   !IF (!eval(!N_CASES) > 1) !THEN  
       MEANS TABLES = VAR1 VAR2 VAR3.  
   !IFEND
!enddefine.

Now running the macro will produce nothing if there is just one line in your data, and will run means if there was more than one line:

!cond_means.

Upvotes: 1

Related Questions