* ======================================================================= File name: min_and_max.SPS Written by: Bruce Weaver, bweaver@lakeheadu.ca Date: 06-Oct-2004 Notes: Find minimum and maximum values using scratch variables . * ======================================================================= . data list list /grp x (2f5.0). begin data. 1 45 1 77 1 59 2 44 2 37 2 50 3 88 3 91 3 79 end data. numeric max.all min.all max.grp min.grp (f5.0). var lab max.all 'Overall maximum' min.all 'Overall minimum' max.grp 'Group maximum' min.grp 'Group minimum'. * Find OVERALL maximum . sort cases by x (d). /* Sort by X, descending; so MAX value is on first row . if ($casenum eq 1) #max = x . compute max.all = #max . exe . * Find GROUP maximum . sort cases by grp (a) x (d). compute #newgrp = ($casenum=1) or (grp ne lag(grp)). if #newgrp #max = x . compute max.grp = #max . exe . * Find OVERALL minimum . sort cases by x (a). /* Sort by X, ascending; so MIN value is on first row . if ($casenum eq 1) #min = x . compute min.all = #min . exe . * Find GROUP minimum . sort cases by grp (a) x (a). compute #newgrp = ($casenum=1) or (grp ne lag(grp)). if #newgrp #min = x . compute min.grp = #min . exe . * Now show that it worked. list. * This method works because SCRATCH VARIABLES (i.e., variables that * start with #) maintain their value from one case to the next. * So in the OVERALL MAX example, after the cases are sorted in descending * order of X, the maximum value is on row one. On case 1, the sratch variable * #max is assigned that maximum value. Then on case 1 AND all subsequent cases, * the value of #max (which remains constant) is assigned to variable MAX.ALL . * The explanation is the same for the other examples, but is slightly more * complicated for the GROUP MAX and MIN examples, because the values of #max * and #min have to be reset on cases where variable GRP is different than * on the previous record. * FINALLY, note that scratch variables are only maintained until * the COMPUTE statements have finished executing. They are, in * other words, TEMPORARY VARIABLES . * End of file. * ======================================================================= .