Examples (LEAVE command)

Correct vs. Invalid Specifications for LEAVE

DATA LIST LIST /Var1 Var2 Var3.
BEGIN DATA
1 2 3
4 5 6
7 8 9
END DATA. 

*this is the correct form.
COMPUTE TotalVar1=TotalVar1+Var1.
LEAVE TotalVar1.

*this will change the value of Var2 but LEAVE will fail, 
 generating an error because Var2 already exists.
COMPUTE Var2=Var2+Var2.
LEAVE Var2.

*this will fail, generating an error because the LEAVE command
 occurs before the command that defines the variable named on LEAVE.
LEAVE TotalVar3.
COMPUTE TotalVar3=TotalVar3+Var3.

LIST.

Running Total

COMPUTE TSALARY=TSALARY+SALARY.
LEAVE TSALARY.
FORMAT TSALARY (DOLLAR8)/ SALARY (DOLLAR7).
  • These commands keep a running total of salaries across all cases. SALARY is the variable containing the employee’s salary, and TSALARY is the new variable containing the cumulative salaries for all previous cases.
  • For the first case, TSALARY is initialized to 0, and TSALARY equals SALARY. For the rest of the cases, TSALARY stores the cumulative totals for SALARY.
  • LEAVE follows COMPUTE because TSALARY must first be defined before it can be specified on LEAVE.
  • If LEAVE were not specified for this computation, TSALARY would be initialized to system-missing for all cases. TSALARY would remain system-missing because its value would be missing for every computation.

Separate Sums for Each Category of a Grouping Variable

SORT CASES DEPT.
IF DEPT NE LAG(DEPT,1) TSALARY=0.   /*Initialize for new dept
COMPUTE TSALARY=TSALARY+SALARY.     /*Sum salaries
LEAVE TSALARY.                    /*Prevent  initialization  each case
FORMAT TSALARY (DOLLAR8)/ SALARY (DOLLAR7).
  • These commands accumulate a sum across cases for each department.
  • SORT first sorts cases by the values of variable DEPT.
  • IF specifies that if the value of DEPT for the current case is not equal to the value of DEPT for the previous case, TSALARY equals 0. Thus, TSALARY is reset to 0 each time the value of DEPT changes. (For the first case in the file, the logical expression on IF is missing. However, the desired effect is obtained because LEAVE initializes TSALARY to 0 for the first case, independent of the IF statement.)
  • LEAVE prevents TSALARY from being initialized for cases within the same department.