work on docs
[pspp] / doc / transformation.texi
1 @c PSPP - a program for statistical analysis.
2 @c Copyright (C) 2017, 2020 Free Software Foundation, Inc.
3 @c Permission is granted to copy, distribute and/or modify this document
4 @c under the terms of the GNU Free Documentation License, Version 1.3
5 @c or any later version published by the Free Software Foundation;
6 @c with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
7 @c A copy of the license is included in the section entitled "GNU
8 @c Free Documentation License".
9 @c
10 @node Data Manipulation
11 @chapter Data transformations
12 @cindex transformations
13
14 The @pspp{} procedures examined in this chapter manipulate data and
15 prepare the active dataset for later analyses.  They do not produce output,
16 as a rule.
17
18 @menu
19 * AGGREGATE::                   Summarize multiple cases into a single case.
20 * AUTORECODE::                  Automatic recoding of variables.
21 * COMPUTE::                     Assigning a variable a calculated value.
22 * COUNT::                       Counting variables with particular values.
23 * FLIP::                        Exchange variables with cases.
24 * IF::                          Conditionally assigning a calculated value.
25 * RECODE::                      Mapping values from one set to another.
26 * SORT CASES::                  Sort the active dataset.
27 @end menu
28
29 @node AGGREGATE
30 @section AGGREGATE
31 @vindex AGGREGATE
32
33 @display
34 AGGREGATE
35         OUTFILE=@{*,'@var{file_name}',@var{file_handle}@} [MODE=@{REPLACE, ADDVARIABLES@}]
36         /PRESORTED
37         /DOCUMENT
38         /MISSING=COLUMNWISE
39         /BREAK=@var{var_list}
40         /@var{dest_var}['@var{label}']@dots{}=@var{agr_func}(@var{src_vars}, @var{args}@dots{})@dots{}
41 @end display
42
43 @cmd{AGGREGATE} summarizes groups of cases into single cases.
44 Cases are divided into groups that have the same values for one or more
45 variables called @dfn{break variables}.  Several functions are available
46 for summarizing case contents.
47
48 The @subcmd{OUTFILE} subcommand is required and must appear first.  Specify a
49 system file or portable file by file name or file
50 handle (@pxref{File Handles}), or a dataset by its name
51 (@pxref{Datasets}).
52 The aggregated cases are written to this file.  If @samp{*} is
53 specified, then the aggregated cases replace the active dataset's data.
54 Use of @subcmd{OUTFILE} to write a portable file is a @pspp{} extension.
55
56 If @subcmd{OUTFILE=*} is given, then the subcommand @subcmd{MODE} may also be
57 specified.
58 The mode subcommand has two possible values: @subcmd{ADDVARIABLES} or @subcmd{REPLACE}.
59 In @subcmd{REPLACE} mode, the entire active dataset is replaced by a new dataset
60 which contains just the break variables and the destination varibles.
61 In this mode, the new file contains as many cases as there are
62 unique combinations of the break variables.
63 In @subcmd{ADDVARIABLES} mode, the destination variables are appended to
64 the existing active dataset.
65 Cases which have identical combinations of values in their break
66 variables, receive identical values for the destination variables.
67 The number of cases in the active dataset remains unchanged.
68 Note that if @subcmd{ADDVARIABLES} is specified, then the data @emph{must} be
69 sorted on the break variables.
70
71 By default, the active dataset is sorted based on the break variables
72 before aggregation takes place.  If the active dataset is already sorted
73 or otherwise grouped in terms of the break variables, specify
74 @subcmd{PRESORTED} to save time.
75 @subcmd{PRESORTED} is assumed if @subcmd{MODE=ADDVARIABLES} is used.
76
77 Specify @subcmd{DOCUMENT} to copy the documents from the active dataset into the
78 aggregate file (@pxref{DOCUMENT}).  Otherwise, the aggregate file does
79 not contain any documents, even if the aggregate file replaces the
80 active dataset.
81
82 Normally, only a single case (for @subcmd{SD} and @subcmd{SD}., two cases) need be
83 non-missing in each group for the aggregate variable to be
84 non-missing.  Specifying @subcmd{/MISSING=COLUMNWISE} inverts this behavior, so
85 that the aggregate variable becomes missing if any aggregated value is
86 missing.
87
88 If @subcmd{PRESORTED}, @subcmd{DOCUMENT}, or @subcmd{MISSING} are specified, they must appear
89 between @subcmd{OUTFILE} and @subcmd{BREAK}.
90
91 At least one break variable must be specified on @subcmd{BREAK}, a
92 required subcommand.  The values of these variables are used to divide
93 the active dataset into groups to be summarized.  In addition, at least
94 one @var{dest_var} must be specified.
95
96 One or more sets of aggregation variables must be specified.  Each set
97 comprises a list of aggregation variables, an equals sign (@samp{=}),
98 the name of an aggregation function (see the list below), and a list
99 of source variables in parentheses.  Some aggregation functions expect
100 additional arguments following the source variable names.
101
102 Aggregation variables typically are created with no variable label,
103 value labels, or missing values.  Their default print and write
104 formats depend on the aggregation function used, with details given in
105 the table below.  A variable label for an aggregation variable may be
106 specified just after the variable's name in the aggregation variable
107 list.
108
109 Each set must have exactly as many source variables as aggregation
110 variables.  Each aggregation variable receives the results of applying
111 the specified aggregation function to the corresponding source
112 variable.  The @subcmd{MEAN}, @subcmd{MEDIAN}, @subcmd{SD}, and @subcmd{SUM}
113 aggregation functions may only be
114 applied to numeric variables.  All the rest may be applied to numeric
115 and string variables.
116
117 The available aggregation functions are as follows:
118
119 @table @asis
120 @item @subcmd{FGT(@var{var_name}, @var{value})}
121 Fraction of values greater than the specified constant.  The default
122 format is F5.3.
123
124 @item @subcmd{FIN(@var{var_name}, @var{low}, @var{high})}
125 Fraction of values within the specified inclusive range of constants.
126 The default format is F5.3.
127
128 @item @subcmd{FLT(@var{var_name}, @var{value})}
129 Fraction of values less than the specified constant.  The default
130 format is F5.3.
131
132 @item @subcmd{FIRST(@var{var_name})}
133 First non-missing value in break group.  The aggregation variable
134 receives the complete dictionary information from the source variable.
135 The sort performed by @cmd{AGGREGATE} (and by @cmd{SORT CASES}) is stable.
136 This means that
137 the first case with particular values for the break variables before
138 sorting is also the first case in that break group after sorting.
139
140 @item @subcmd{FOUT(@var{var_name}, @var{low}, @var{high})}
141 Fraction of values strictly outside the specified range of constants.
142 The default format is F5.3.
143
144 @item @subcmd{LAST(@var{var_name})}
145 Last non-missing value in break group.  The aggregation variable
146 receives the complete dictionary information from the source variable.
147 The sort performed by @cmd{AGGREGATE} (and by @cmd{SORT CASES}) is stable.
148
149 @item @subcmd{MAX(@var{var_name})}
150 Maximum value.  The aggregation variable receives the complete
151 dictionary information from the source variable.
152
153 @item @subcmd{MEAN(@var{var_name})}
154 Arithmetic mean.  Limited to numeric values.  The default format is
155 F8.2.
156
157 @item @subcmd{MEDIAN(@var{var_name})}
158 The median value.  Limited to numeric values.  The default format is F8.2.
159
160 @item @subcmd{MIN(@var{var_name})}
161 Minimum value.  The aggregation variable receives the complete
162 dictionary information from the source variable.
163
164 @item @subcmd{N(@var{var_name})}
165 Number of non-missing values.  The default format is F7.0 if weighting
166 is not enabled, F8.2 if it is (@pxref{WEIGHT}).
167
168 @item @subcmd{N}
169 Number of cases aggregated to form this group.  The default format is
170 F7.0 if weighting is not enabled, F8.2 if it is (@pxref{WEIGHT}).
171
172 @item @subcmd{NMISS(@var{var_name})}
173 Number of missing values.  The default format is F7.0 if weighting is
174 not enabled, F8.2 if it is (@pxref{WEIGHT}).
175
176 @item @subcmd{NU(@var{var_name})}
177 Number of non-missing values.  Each case is considered to have a weight
178 of 1, regardless of the current weighting variable (@pxref{WEIGHT}).
179 The default format is F7.0.
180
181 @item @subcmd{NU}
182 Number of cases aggregated to form this group.  Each case is considered
183 to have a weight of 1, regardless of the current weighting variable.
184 The default format is F7.0.
185
186 @item @subcmd{NUMISS(@var{var_name})}
187 Number of missing values.  Each case is considered to have a weight of
188 1, regardless of the current weighting variable.  The default format is F7.0.
189
190 @item @subcmd{PGT(@var{var_name}, @var{value})}
191 Percentage between 0 and 100 of values greater than the specified
192 constant.  The default format is F5.1.
193
194 @item @subcmd{PIN(@var{var_name}, @var{low}, @var{high})}
195 Percentage of values within the specified inclusive range of
196 constants.  The default format is F5.1.
197
198 @item @subcmd{PLT(@var{var_name}, @var{value})}
199 Percentage of values less than the specified constant.  The default
200 format is F5.1.
201
202 @item @subcmd{POUT(@var{var_name}, @var{low}, @var{high})}
203 Percentage of values strictly outside the specified range of
204 constants.  The default format is F5.1.
205
206 @item @subcmd{SD(@var{var_name})}
207 Standard deviation of the mean.  Limited to numeric values.  The
208 default format is F8.2.
209
210 @item @subcmd{SUM(@var{var_name})}
211 Sum.  Limited to numeric values.  The default format is F8.2.
212 @end table
213
214 Aggregation functions compare string values in terms of internal
215 character codes.
216 On most modern computers, this is  @acronym{ASCII} or a superset thereof.
217
218 The aggregation functions listed above exclude all user-missing values
219 from calculations.  To include user-missing values, insert a period
220 (@samp{.}) at the end of the function name.  (@i{e.g.}@: @samp{SUM.}).
221 (Be aware that specifying such a function as the last token on a line
222 causes the period to be interpreted as the end of the command.)
223
224 @cmd{AGGREGATE} both ignores and cancels the current @cmd{SPLIT FILE}
225 settings (@pxref{SPLIT FILE}).
226
227 @subsection Aggregate Example
228
229 The @file{personnel.sav} dataset provides the occupations and salaries of
230 many individuals.  For many purposes however such detailed information is
231 not interesting, but often the aggregated statistics of each occupation are
232 of interest.  In @ref{aggregate:ex} the @cmd{AGGREGATE} command is used
233 to calculate the mean, the median and the standard deviation of each
234 occupation.
235
236 @float Example, aggregate:ex
237 @psppsyntax {aggregate.sps}
238 @caption {Calculating aggregated statistics from the @file{personnel.sav} file.}
239 @end float
240
241 Since we chose the @samp{MODE = REPLACE} option, in @ref{aggregate:res} cases
242 for the individual persons are no longer present.  They have each been replaced
243 by a single case per aggregated value.
244
245 @float Results, aggregate:res
246 @psppoutput {aggregate}
247 @caption {Aggregated mean, median and standard deviation per @exvar{occupation}.}
248 @end float
249
250 Note that some values for the standard deviation are blank.
251 This is because there is only one case with the respective
252 occupation.
253
254
255 @node AUTORECODE
256 @section AUTORECODE
257 @vindex AUTORECODE
258
259 @display
260 AUTORECODE VARIABLES=@var{src_vars} INTO @var{dest_vars}
261         [ /DESCENDING ]
262         [ /PRINT ]
263         [ /GROUP ]
264         [ /BLANK = @{VALID, MISSING@} ]
265 @end display
266
267 The @cmd{AUTORECODE} procedure considers the @var{n} values that a variable
268 takes on and maps them onto values 1@dots{}@var{n} on a new numeric
269 variable.
270
271 Subcommand @subcmd{VARIABLES} is the only required subcommand and must come
272 first.  Specify @subcmd{VARIABLES}, an equals sign (@samp{=}), a list of source
273 variables, @subcmd{INTO}, and a list of target variables.  There must the same
274 number of source and target variables.  The target variables must not
275 already exist.
276
277 @cmd{AUTORECODE} ordinarily assigns each increasing non-missing value
278 of a source variable (for a string, this is based on character code
279 comparisons) to consecutive values of its target variable.  For
280 example, the smallest non-missing value of the source variable is
281 recoded to value 1, the next smallest to 2, and so on.  If the source
282 variable has user-missing values, they are recoded to
283 consecutive values just above the non-missing values.  For example, if
284 a source variables has seven distinct non-missing values, then the
285 smallest missing value would be recoded to 8, the next smallest to 9,
286 and so on.
287
288 Use @subcmd{DESCENDING} to reverse the sort order for non-missing
289 values, so that the largest non-missing value is recoded to 1, the
290 second-largest to 2, and so on.  Even with @subcmd{DESCENDING},
291 user-missing values are still recoded in ascending order just above
292 the non-missing values.
293
294 The system-missing value is always recoded into the system-missing
295 variable in target variables.
296
297 If a source value has a value label, then that value label is retained
298 for the new value in the target variable.  Otherwise, the source value
299 itself becomes each new value's label.
300
301 Variable labels are copied from the source to target variables.
302
303 @subcmd{PRINT} is currently ignored.
304
305 The @subcmd{GROUP} subcommand is relevant only if more than one variable is to be
306 recoded.   It causes a single mapping between source and target values to
307 be used, instead of one map per variable.  With @subcmd{GROUP},
308 user-missing values are taken from the first source variable that has
309 any user-missing values.
310
311 If @subcmd{/BLANK=MISSING} is given, then string variables which contain only
312 whitespace are recoded as SYSMIS.  If @subcmd{/BLANK=VALID} is specified then they
313 are allocated a value like any other.  @subcmd{/BLANK} is not relevant
314 to numeric values. @subcmd{/BLANK=VALID} is the default.
315
316 @cmd{AUTORECODE} is a procedure.  It causes the data to be read.
317
318 @subsection Autorecode Example
319
320 In the file @file{personnel.sav}, the variable @exvar{occupation} is a string
321 variable.   Except for data of a purely commentary nature, string variables
322 are generally a bad idea.  One reason is that data entry errors are easily
323 overlooked.  This has happened in @file{personnel.sav}; one entry which should
324 read ``Scientist'' has been mistyped as ``Scrientist''.  In @ref{autorecode:ex}
325 first, this error is corrected by the @cmd{DO IF} clause,
326 @footnote{One must use care when correcting such data input errors rather than
327 msimply marking them as missing.  For example, if an occupation has been entered
328 ``Barister'', did the person mean ``Barrister'' or did she mean ``Barista''?}
329 then we use @cmd{AUTORECODE} to
330 create a new numeric variable which takes recoded values of @exvar{occupation}.
331 Finally, we remove the old variable and rename the new variable to
332 the name of the old variable.
333
334 @float Example, autorecode:ex
335 @psppsyntax {autorecode.sps}
336 @caption {Changing a string variable to a numeric variable using @cmd{AUTORECODE}
337 after correcting a data entry error}
338 @end float
339
340
341 @float Screenshot, autorecode:scr
342 @psppimage {autorecode}
343 @caption {Autorecode dialog box set to recode @exvar{occupation} to @exvar{occ}}
344 @end float
345
346 Notice in @ref{autorecode:res}, how  the new variable has been automatically
347 allocated value labels which correspond to the strings of the old variable.
348 This means that in future analyses the descriptive strings are reported instead
349 of the numeric values.
350
351 @float Result, autorecode:res
352 @psppoutput {autorecode}
353 @caption {The properties of the @exvar{occupation} variable following @cmd{AUTORECODE}}
354 @end float
355
356
357 @node COMPUTE
358 @section COMPUTE
359 @vindex COMPUTE
360
361 @display
362 COMPUTE @var{variable} = @var{expression}.
363 @end display
364   or
365 @display
366 COMPUTE vector(@var{index}) = @var{expression}.
367 @end display
368
369 @cmd{COMPUTE} assigns the value of an expression to a target
370 variable.  For each case, the expression is evaluated and its value
371 assigned to the target variable.  Numeric and string
372 variables may be assigned.  When a string expression's width differs
373 from the target variable's width, the string result of the expression
374 is truncated or padded with spaces on the right as necessary.  The
375 expression and variable types must match.
376
377 For numeric variables only, the target variable need not already
378 exist.  Numeric variables created by @cmd{COMPUTE} are assigned an
379 @code{F8.2} output format.  String variables must be declared before
380 they can be used as targets for @cmd{COMPUTE}.
381
382 The target variable may be specified as an element of a vector
383 (@pxref{VECTOR}).  In this case, an expression @var{index} must be
384 specified in parentheses following the vector name.  The expression @var{index}
385 must evaluate to a numeric value that, after rounding down
386 to the nearest integer, is a valid index for the named vector.
387
388 Using @cmd{COMPUTE} to assign to a variable specified on @cmd{LEAVE}
389 (@pxref{LEAVE}) resets the variable's left state.  Therefore,
390 @code{LEAVE} should be specified following @cmd{COMPUTE}, not before.
391
392 @cmd{COMPUTE} is a transformation.  It does not cause the active dataset to be
393 read.
394
395 When @cmd{COMPUTE} is specified following @cmd{TEMPORARY}
396 (@pxref{TEMPORARY}), the @cmd{LAG} function may not be used
397 (@pxref{LAG}).
398
399 @subsection Compute Examples
400
401 The dataset @file{physiology.sav} contains the height and weight of persons.
402 For some purposes, neither height nor weight alone is of interest.
403 Epidemiologists are often more interested in the @dfn{body mass index} which
404 can sometimes be used as a predictor for clinical conditions.
405 The body mass index is defined as the weight of the person in kilograms divided
406 by the square of the person's height in metres.
407 @footnote{Since BMI is a quantity with a ratio scale and has units, the term ``index''
408 is a misnomer, but that is what it is called.}
409
410 @float Example, bmi:ex
411 @psppsyntax {compute.sps}
412 @caption {Computing the body mass index from @exvar{weight} and @exvar{height}}
413 @end float
414
415 @ref{bmi:ex} shows how you can use @cmd{COMPUTE} to generate a new variable called
416 @exvar{bmi} and have every case's value calculated from the existing values of
417 @exvar{weight} and @exvar{height}.
418 It also shows how you can add a label to this new variable (@pxref{VARIABLE LABELS}),
419 so that a more descriptive label appears in subsequent analyses, and this can be seen
420 in the ouput from the @cmd{DESCRIPTIVES} command in @ref{bmi:res}.
421
422 @float Screenshot, bmi:scr
423 @psppimage {compute}
424 @caption {Using the dialog box to generate a new variable and compute its values}
425 @end float
426
427 The expression which follows the @samp{=} sign can be as complicated as necessary.
428 @xref{Expressions} for a precise description of the language accepted.
429 Normally it is easiest to enter the code directly, however there is a dialog box
430 available if desired.  This is illustrated in @ref{bmi:scr}.
431 One advantage is that it offers a list of mathematical
432 functions which can be selected and pasted into the expression.
433
434 @float Results, bmi:res
435 @psppoutput {compute}
436 @caption {An analysis which includes @exvar{bmi} in its results}
437 @end float
438
439
440
441 @node COUNT
442 @section COUNT
443 @vindex COUNT
444
445 @display
446 COUNT @var{var_name} = @var{var}@dots{} (@var{value}@dots{})
447     [/@var{var_name} = @var{var}@dots{} (@var{value}@dots{})]@dots{}
448
449 Each @var{value} takes one of the following forms:
450         @var{number}
451         @var{string}
452         @var{num1} THRU @var{num2}
453         MISSING
454         SYSMIS
455 where @var{num1} is a numeric expression or the words @subcmd{LO}  or @subcmd{LOWEST}
456       and @var{num2} is a numeric expression  or @subcmd{HI} or @subcmd{HIGHEST}.
457 @end display
458
459 @cmd{COUNT} creates or replaces a numeric @dfn{target} variable that
460 counts the occurrence of a @dfn{criterion} value or set of values over
461 one or more @dfn{test} variables for each case.
462
463 The target variable values are always nonnegative integers.  They are
464 never missing.  The target variable is assigned an F8.2 output format.
465 @xref{Input and Output Formats}.  Any variables, including
466 string variables, may be test variables.
467
468 User-missing values of test variables are treated just like any other
469 values.  They are @strong{not} treated as system-missing values.
470 User-missing values that are criterion values or inside ranges of
471 criterion values are counted as any other values.  However (for numeric
472 variables), keyword @subcmd{MISSING} may be used to refer to all system-
473 and user-missing values.
474
475 @cmd{COUNT} target variables are assigned values in the order
476 specified.  In the command @subcmd{COUNT @var{A}=@var{A} @var{B}(1) /@var{B}=@var{A} @var{B}(2).}, the
477 following actions occur:
478
479 @itemize @minus
480 @item
481 The number of occurrences of 1 between @var{A} and @var{B} is counted.
482
483 @item
484 @var{A} is assigned this value.
485
486 @item
487 The number of occurrences of 1 between @var{B} and the @strong{new}
488 value of @var{A} is counted.
489
490 @item
491 @var{B} is assigned this value.
492 @end itemize
493
494 Despite this ordering, all @cmd{COUNT} criterion variables must exist
495 before the procedure is executed---they may not be created as target
496 variables earlier in the command!  Break such a command into two
497 separate commands.
498
499 @subsection Count Examples
500
501 In the survey results in dataset @file{hotel.sav} a manager wishes
502 to know how many respondents answered with low valued answers to questions
503 @exvar{v1}, @exvar{v2} and @exvar{v3}.  This can be found using the code
504 in @ref{count:ex}.  Specifically, this code creates a new variable, and
505 populates it with the number of values in @exvar{v1}--@exvar{v2} which
506 are 2 or lower.
507
508 @float Example, count:ex
509 @psppsyntax {count.sps}
510 @caption {Counting low values to responses @exvar{v1}, @exvar{v2} and @exvar{v3}}
511 @end float
512
513 In @ref{count:ex} the @cmd{COUNT} transformation creates a new variable, @exvar{low_counts} and
514 its values are shown using the @cmd{LIST} command.
515
516 If using the graphic user interface, a two step process must be used to set
517 up the @cmd{COUNT} transformation.  The first dialog box (@ref{count:scr}) provides for the
518 variables to be chosen.
519 Then, one must click on the button marked ``Define Values...'' to reveal
520 the dialog box for selecting the values to count.
521
522 @float Screenshot, count:scr
523 @psppimage {count}
524 @caption {The variables @exvar{v1}, @exvar{v2} and @exvar{v3} selected, ready
525 to define values to count}
526 @end float
527
528 In this dialog box, you must select the values you wish to count
529 --- in this case all values up to and including 2 --- as shown in @ref{count-define:scr}
530 and click ``Add''.  As many ranges or may be added as you desire.
531 When all desired ranges have been added click ``Continue''.
532
533 @float Screenshot, count-define:scr
534 @psppimage {count-define}
535 @caption {Count ``Define Values'' dialog with @samp{lowest thru 2} selected}
536 @end float
537
538 In @ref{count:res} we can see the values of @exvar{low_counts} after the @cmd{COUNT}
539 transformation has completed.  The first value is 1, because there is only one
540 variable amoung @exvar{v1}, @exvar{v2} and @exvar{3} which has a value of 2 or less.
541 The second value is 2, because both @exvar{v1} and @exvar{v2} are 2 or less.
542
543 @float Result, count:res
544 @psppoutput {count}
545 @caption {The values of @exvar{v1}, @exvar{v2}, @exvar{v3} and @exvar{low_counts} after
546 the @cmd{COUNT} transformation has run}
547 @end float
548
549
550 @node FLIP
551 @section FLIP
552 @vindex FLIP
553
554 @display
555 FLIP /VARIABLES=@var{var_list} /NEWNAMES=@var{var_name}.
556 @end display
557
558 @cmd{FLIP} transposes rows and columns in the active dataset.  It
559 causes cases to be swapped with variables, and vice versa.
560
561 All variables in the transposed active dataset are numeric.  String
562 variables take on the system-missing value in the transposed file.
563
564 @subcmd{N} subcommands are required.  If specified, the @subcmd{VARIABLES} subcommand
565 selects variables to be transformed into cases, and variables not
566 specified are discarded.  If the @subcmd{VARIABLES} subcommand is omitted, all
567 variables are selected for transposition.
568
569 The variables specified by @subcmd{NEWNAMES}, which must be a
570 string variable, is
571 used to give names to the variables created by @cmd{FLIP}.  Only the
572 first 8 characters of the variable are used.  If
573 @subcmd{NEWNAMES} is not
574 specified then the default is a variable named @exvar{CASE_LBL}, if it exists.
575 If it does not then the variables created by @cmd{FLIP} are named VAR000
576 through VAR999, then VAR1000, VAR1001, and so on.
577
578 When a @subcmd{NEWNAMES} variable is available, the names must be canonicalized
579 before becoming variable names.  Invalid characters are replaced by
580 letter @samp{V} in the first position, or by @samp{_} in subsequent
581 positions.  If the name thus generated is not unique, then numeric
582 extensions are added, starting with 1, until a unique name is found or
583 there are no remaining possibilities.  If the latter occurs then the
584 @cmd{FLIP} operation aborts.
585
586 The resultant dictionary contains a @exvar{CASE_LBL} variable, a string
587 variable of width 8, which stores the names of the variables in the
588 dictionary before the transposition.  Variables names longer than 8
589 characters are truncated.  If @cmd{FLIP} is called again on
590 this dataset, the @exvar{CASE_LBL} variable can be passed to the @subcmd{NEWNAMES}
591 subcommand to recreate the original variable names.
592
593 @cmd{FLIP} honors @cmd{N OF CASES} (@pxref{N OF CASES}).  It ignores
594 @cmd{TEMPORARY} (@pxref{TEMPORARY}), so that ``temporary''
595 transformations become permanent.
596
597 @subsection Flip Examples
598
599
600 In @ref{flip:ex}, data has been entered using @cmd{DATA LIST} (@pxref{DATA LIST})
601 such that the first variable in the dataset is a string variable containing
602 a description of the other data for the case.
603 Clearly this is not a convenient arrangement for performing statistical analyses,
604 so it would have been better to think a little more carefully about how the data
605 should have been arranged.
606 However often the data is provided by some third party source, and you have
607 no control over the form.
608 Fortunately, we can use @cmd{FLIP} to exchange the variables
609 and cases in the active dataset.
610
611 @float Example, flip:ex
612 @psppsyntax {flip.sps}
613 @caption {Using @cmd{FLIP} to exchange variables and cases in a dataset}
614 @end float
615
616 As you can see in @ref{flip:res} before the @cmd{FLIP} command has run there
617 are seven variables (six containing data and one for the heading) and three cases.
618 Afterwards there are four variables (one per case, plus the @exvar{CASE_LBL} variable)
619 and six cases.
620 You can delete the @exvar{CASE_LBL} variable (@pxref{DELETE VARIABLES}) if you don't need it.
621
622 @float Results, flip:res
623 @psppoutput {flip}
624 @caption {The results of using @cmd{FLIP} to exchange variables and cases in a dataset}
625 @end float
626
627
628 @node IF
629 @section IF
630 @vindex IF
631
632 @display
633 IF @var{condition} @var{variable}=@var{expression}.
634 @end display
635   or
636 @display
637 IF @var{condition} vector(@var{index})=@var{expression}.
638 @end display
639
640 The @cmd{IF} transformation conditionally assigns the value of a target
641 expression to a target variable, based on the truth of a test
642 expression.
643
644 Specify a boolean-valued expression (@pxref{Expressions}) to be tested
645 following the @cmd{IF} keyword.  This expression is evaluated for each case.
646 If the value is true, then the value of the expression is computed and
647 assigned to the specified variable.  If the value is false or missing,
648 nothing is done.  Numeric and string variables may be
649 assigned.  When a string expression's width differs from the target
650 variable's width, the string result of the expression is truncated or
651 padded with spaces on the right as necessary.  The expression and
652 variable types must match.
653
654 The target variable may be specified as an element of a vector
655 (@pxref{VECTOR}).  In this case, a vector index expression must be
656 specified in parentheses following the vector name.  The index
657 expression must evaluate to a numeric value that, after rounding down
658 to the nearest integer, is a valid index for the named vector.
659
660 Using @cmd{IF} to assign to a variable specified on @cmd{LEAVE}
661 (@pxref{LEAVE}) resets the variable's left state.  Therefore,
662 @code{LEAVE} should be specified following @cmd{IF}, not before.
663
664 When @cmd{IF} is specified following @cmd{TEMPORARY}
665 (@pxref{TEMPORARY}), the @cmd{LAG} function may not be used
666 (@pxref{LAG}).
667
668 @node RECODE
669 @section RECODE
670 @vindex RECODE
671
672 The @cmd{RECODE} command is used to transform existing values into other,
673 user specified values.
674 The general form is:
675
676 @display
677 RECODE @var{src_vars}
678         (@var{src_value} @var{src_value} @dots{} = @var{dest_value})
679         (@var{src_value} @var{src_value} @dots{} = @var{dest_value})
680         (@var{src_value} @var{src_value} @dots{} = @var{dest_value}) @dots{}
681          [INTO @var{dest_vars}].
682 @end display
683
684 Following the @cmd{RECODE} keyword itself comes @var{src_vars} which is a list
685 of variables whose values are to be transformed.
686 These variables may be string variables or they may be numeric.
687 However the list must be homogeneous; you may not mix string variables and
688 numeric variables in the same recoding.
689
690 After the list of source variables, there should be one or more @dfn{mappings}.
691 Each mapping is enclosed in parentheses, and contains the source values and
692 a destination value separated by a single @samp{=}.
693 The source values are used to specify the values in the dataset which
694 need to change, and the destination value specifies the new value
695 to which they should be changed.
696 Each @var{src_value} may take one of the following forms:
697 @table @asis
698 @item @var{number}
699 If the source variables are numeric then @var{src_value} may be a literal
700 number.
701 @item @var{string}
702 If the source variables are string variables then @var{src_value} may be a
703 literal string (like all strings, enclosed in single or double quotes).
704 @item @var{num1} THRU @var{num2}
705 This form is valid only when the source variables are numeric.
706 It specifies all values in the range between @var{num1} and @var{num2},
707 including both endpoints of the range.  By convention, @var{num1}
708 should be less than @var{num2}.
709 Open-ended ranges may be specified using @samp{LO} or @samp{LOWEST}
710 for @var{num1}
711 or @samp{HI} or @samp{HIGHEST} for @var{num2}.
712 @item @samp{MISSING}
713 The literal keyword @samp{MISSING} matches both system missing and user
714 missing values.
715 It is valid for both numeric and string variables.
716 @item @samp{SYSMIS}
717 The literal keyword @samp{SYSMIS} matches system missing
718 values.
719 It is valid for both numeric variables only.
720 @item @samp{ELSE}
721 The @samp{ELSE} keyword may be used to match any values which are
722 not matched by any other @var{src_value} appearing in the command.
723 If this keyword appears, it should be used in the last mapping of the
724 command.
725 @end table
726
727 After the source variables comes an @samp{=} and then the @var{dest_value}.
728 The @var{dest_value} may take any of the following forms:
729 @table @asis
730 @item @var{number}
731 A literal numeric value to which the source values should be changed.
732 This implies the destination variable must be numeric.
733 @item @var{string}
734 A literal string value (enclosed in quotation marks) to which the source
735 values should be changed.
736 This implies the destination variable must be a string variable.
737 @item @samp{SYSMIS}
738 The keyword @samp{SYSMIS} changes the value to the system missing value.
739 This implies the destination variable must be numeric.
740 @item @samp{COPY}
741 The special keyword @samp{COPY} means that the source value should not be
742 modified, but
743 copied directly to the destination value.
744 This is meaningful only if @samp{INTO @var{dest_vars}} is specified.
745 @end table
746
747 Mappings are considered from left to right.
748 Therefore, if a value is matched by a @var{src_value} from more than
749 one mapping, the first (leftmost) mapping which matches is considered.
750 Any subsequent matches are ignored.
751
752 The clause @samp{INTO @var{dest_vars}} is optional.
753 The behaviour of the command is slightly different depending on whether it
754 appears or not.
755
756 If @samp{INTO @var{dest_vars}} does not appear, then values are recoded
757 ``in place''.
758 This means that the recoded values are written back to the
759 source variables from whence the original values came.
760 In this case, the @var{dest_value} for every mapping must imply a value which
761 has the same type as the @var{src_value}.
762 For example, if the source value is a string value, it is not permissible for
763 @var{dest_value} to be @samp{SYSMIS} or another forms which implies a numeric
764 result.
765 It is also not permissible for @var{dest_value} to be  longer than the width
766 of the source variable.
767
768 The following example two numeric variables @var{x} and @var{y} are recoded
769 in place.
770 Zero is recoded to 99, the values 1 to 10 inclusive are unchanged,
771 values 1000 and higher are recoded to the system-missing value and all other
772 values are changed to 999:
773 @example
774 recode @var{x} @var{y}
775         (0 = 99)
776         (1 THRU 10 = COPY)
777         (1000 THRU HIGHEST = SYSMIS)
778         (ELSE = 999).
779 @end example
780
781 If @samp{INTO @var{dest_vars}} is given, then recoded values are written
782 into the variables specified in @var{dest_vars}, which must therefore
783  contain a list of valid variable names.
784 The number of variables in @var{dest_vars} must be the same as the number
785 of variables in @var{src_vars}
786 and the respective order of the variables in @var{dest_vars} corresponds to
787 the order of @var{src_vars}.
788 That is to say, the recoded value whose
789 original value came from the @var{n}th variable in @var{src_vars} is
790 placed into the @var{n}th variable in @var{dest_vars}.
791 The source variables are unchanged.
792 If any mapping implies a string as its destination value, then the respective
793 destination variable must already exist, or
794 have been declared using @cmd{STRING} or another transformation.
795 Numeric variables however are automatically created if they don't already
796 exist.
797 The following example deals with two source variables, @var{a} and @var{b}
798 which contain string values.  Hence there are two destination variables
799 @var{v1} and @var{v2}.
800 Any cases where @var{a} or @var{b} contain the values @samp{apple},
801 @samp{pear} or @samp{pomegranate} result in @var{v1} or @var{v2} being
802 filled with the string @samp{fruit} whilst cases with
803 @samp{tomato}, @samp{lettuce} or @samp{carrot} result in @samp{vegetable}.
804 Any other values produce the result @samp{unknown}:
805 @example
806 string @var{v1} (a20).
807 string @var{v2} (a20).
808
809 recode @var{a} @var{b}
810         ("apple" "pear" "pomegranate" = "fruit")
811         ("tomato" "lettuce" "carrot" = "vegetable")
812         (ELSE = "unknown")
813         into @var{v1} @var{v2}.
814 @end example
815
816 There is one very special mapping, not mentioned above.
817 If the source variable is a string variable
818 then a mapping may be specified as @samp{(CONVERT)}.
819 This mapping, if it appears must be the last mapping given and
820 the @samp{INTO @var{dest_vars}} clause must also be given and
821 must not refer to a string variable.
822 @samp{CONVERT} causes a number specified as a string to
823 be converted to a numeric value.
824 For example it converts the string @samp{"3"} into the numeric
825 value 3 (note that it does not convert @samp{three} into 3).
826 If the string cannot be parsed as a number, then the system-missing value
827 is assigned instead.
828 In the following example, cases where the value of @var{x} (a string variable)
829 is the empty string, are recoded to 999 and all others are converted to the
830 numeric equivalent of the input value.  The results are placed into the
831 numeric variable @var{y}:
832 @example
833 recode @var{x}
834        ("" = 999)
835         (convert)
836         into @var{y}.
837 @end example
838
839 It is possible to specify multiple recodings on a single command.
840 Introduce additional recodings with a slash (@samp{/}) to
841 separate them from the previous recodings:
842 @example
843 recode
844         @var{a}  (2 = 22) (else = 99)
845         /@var{b} (1 = 3) into @var{z}
846         .
847 @end example
848 @noindent Here we have two recodings. The first affects the source variable
849 @var{a} and recodes in-place the value 2 into 22 and all other values to 99.
850 The second recoding copies the values of @var{b} into the variable @var{z},
851 changing any instances of 1 into 3.
852
853 @node SORT CASES
854 @section SORT CASES
855 @vindex SORT CASES
856
857 @display
858 SORT CASES BY @var{var_list}[(@{D|A@}] [ @var{var_list}[(@{D|A@}] ] ...
859 @end display
860
861 @cmd{SORT CASES} sorts the active dataset by the values of one or more
862 variables.
863
864 Specify @subcmd{BY} and a list of variables to sort by.  By default, variables
865 are sorted in ascending order.  To override sort order, specify @subcmd{(D)} or
866 @subcmd{(DOWN)} after a list of variables to get descending order, or @subcmd{(A)}
867 or @subcmd{(UP)}
868 for ascending order.  These apply to all the listed variables
869 up until the preceding @subcmd{(A)}, @subcmd{(D)}, @subcmd{(UP)} or @subcmd{(DOWN)}.
870
871 The sort algorithms used by @cmd{SORT CASES} are stable.  This means
872 records which have equal values of the sort variables have the
873 same relative order before and after sorting.  Thus,
874 re-sorting an already sorted file does not affect the ordering of
875 cases.
876
877 @cmd{SORT CASES} is a procedure.  It causes the data to be read.
878
879 @cmd{SORT CASES} attempts to sort the entire active dataset in main memory.
880 If workspace is exhausted, it falls back to a merge sort algorithm which
881 creates numerous temporary files.
882
883 @cmd{SORT CASES} may not be specified following @cmd{TEMPORARY}.
884
885 @subsection Sorting Example
886
887 In @ref{sort-cases:ex} the data from the file @file {physiology.sav} is sorted
888 by two variables, @i{viz@:} @exvar{sex} in descending order and @exvar{temperature} in
889 ascending order.
890
891 @float Example, sort-cases:ex
892 @psppsyntax {sort-cases.sps}
893 @caption {Sorting cases  by two variables.}
894 @end float
895
896 In @ref{sort-cases:res} you can see that all the cases with a @exvar{sex} of
897 @samp{1} (female) appear before those with a sex of @samp{0} (male).
898 This is because they have been sorted in descending order.
899 Within each sex, the data is sorted on the @exvar{temperature} variable,
900 this time in ascending order.
901
902 @float Results, sort-cases:res
903 @psppoutput {sort-cases}
904 @caption {The @file{physiology.sav} file after sorting.}
905 @end float
906
907 Note that @cmd{SORT CASES}, like all other transformations, affects only the active file.
908 It does not have any effect upon the @file{physiology.sav} file itself. For that, you
909 would have to rewrite the file using the @cmd{SAVE} command (@pxref{SAVE}).
910
911 When using the graphic user interface, it is often simpler to perform a sort
912 directly from the data view.
913 To do this, switch to the data view.  Select the column corresponding to the
914 variable by which you want to sort and click button 1 and then click button 3.
915 A popup menu will appear like that shown in @ref{sort-simple:scr}.  Select
916 either ``Sort Ascending'' or ``Sort Descending'' from this menu.
917
918 @float Screenshot, sort-simple:scr
919 @psppimage {sort-simple}
920 @caption {Sorting the data on a single variable @exvar{height}}
921 @end float
922
923 However, sometimes you will want to sort on two or more variables, and that is
924 not possible using this method.  In this case, you must either use some code or
925 the ``Sort Cases'' dialog from the Data menu.  @ref{sort:scr} shows the dialog
926 box set up to perform a sort on both @exvar{sex} and @exvar{height}.
927 Note that the order in which you enter the variables is important.  In this case,
928 the data will be first sorted on @exvar{sex}, and then all cases for which @exvar{sex}
929 is the same will then be sorted by @exvar{height}.
930
931 @float Screenshot, sort:scr
932 @psppimage {sort}
933 @caption {Sorting the data on two variables @exvar{sex} and  @exvar{height}}
934 @end float