1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
* To create a new var based on a function of a given variable var1.
* For instance to add a var which equals the sum, sd, median or mean of an other variable.
* This is very useful.
* Raynald Levesque rlevesque@videotron.ca.

DATA LIST FREE /age.
BEGIN DATA
25 35 24 12 52 45 46 35 28 65 21 54 24 52 14 25 36
END DATA.
LIST.

SET CACHE=0.
SET MPRINT=yes.
*///////////////////////////.
DEFINE !newvar (var=!TOKENS(1) 
	/newname=!TOKENS(1) 
	/func=!TOKENS(1))
* Creates var newname equal to the func of var.
* Possible values of func are:
* med , sum, first, last, mean, and any other predefined function of the AGGR command.
COMPUTE dummy=1.

!IF (!func='med') !THEN
!LET !f=first
RANK !var BY dummy
  /TIES=HIGH
  /RFRACTION INTO ranki.
COMPUTE x=ranki-.5.
IF x LT 0 x=x+1.0001.
SORT CASES BY x !var.
!LET !dropl='dummy ranki x'

!ELSE
!LET !f=!func
!LET !dropl='dummy'
!IFEND

AGGREGATE OUTFILE='c:\\temp\\out1.sav'
  /PRESORTED
  /BREAK=dummy
  /!newname=!f(!var).

MATCH FILES FILE=* /TABLE='c:\\temp\\out1.sav' /BY dummy /DROP !dropl.
EXECUTE.
!ENDDEFINE.
*///////////////////////////.

* Examples of usage of the macro.
!newvar var=age newname=med_age 	func=med.
!newvar var=age newname=avg_age 	func=mean.
!newvar var=age newname=nbcases 	func=n.
!newvar var=age newname=sd_age 	func=sd.