1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2006, 2009, 2010, 2011, 2012, 2013, 2014, 2016 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 - How to calculate significance of some symmetric and directional measures?
20 - How to calculate ASE for symmetric Somers ' d?
21 - How to calculate ASE for Goodman and Kruskal's tau?
22 - How to calculate approx. T of symmetric uncertainty coefficient?
30 #include <gsl/gsl_cdf.h>
34 #include "data/case.h"
35 #include "data/casegrouper.h"
36 #include "data/casereader.h"
37 #include "data/data-out.h"
38 #include "data/dataset.h"
39 #include "data/dictionary.h"
40 #include "data/format.h"
41 #include "data/value-labels.h"
42 #include "data/variable.h"
43 #include "language/command.h"
44 #include "language/stats/freq.h"
45 #include "language/dictionary/split-file.h"
46 #include "language/lexer/lexer.h"
47 #include "language/lexer/variable-parser.h"
48 #include "libpspp/array.h"
49 #include "libpspp/assertion.h"
50 #include "libpspp/compiler.h"
51 #include "libpspp/hash-functions.h"
52 #include "libpspp/hmap.h"
53 #include "libpspp/hmapx.h"
54 #include "libpspp/message.h"
55 #include "libpspp/misc.h"
56 #include "libpspp/pool.h"
57 #include "libpspp/str.h"
58 #include "output/tab.h"
59 #include "output/chart-item.h"
60 #include "output/charts/barchart.h"
62 #include "gl/minmax.h"
63 #include "gl/xalloc.h"
67 #define _(msgid) gettext (msgid)
68 #define N_(msgid) msgid
76 missing=miss:!table/include/report;
77 count=roundwhat:asis/case/!cell,
78 roundhow:!round/truncate;
79 +write[wr_]=none,cells,all;
80 +format=val:!avalue/dvalue,
82 tabl:!tables/notables,
86 +cells[cl_]=count,expected,row,column,total,residual,sresidual,
88 +statistics[st_]=chisq,phi,cc,lambda,uc,none,btau,ctau,risk,gamma,d,
94 /* Number of chi-square statistics. */
97 /* Number of symmetric statistics. */
100 /* Number of directional statistics. */
101 #define N_DIRECTIONAL 13
104 /* Indexes into the 'vars' member of struct crosstabulation and
105 struct crosstab member. */
108 ROW_VAR = 0, /* Row variable. */
109 COL_VAR = 1 /* Column variable. */
110 /* Higher indexes cause multiple tables to be output. */
113 /* A crosstabulation of 2 or more variables. */
114 struct crosstabulation
116 struct crosstabs_proc *proc;
117 struct fmt_spec weight_format; /* Format for weight variable. */
118 double missing; /* Weight of missing cases. */
120 /* Variables (2 or more). */
122 const struct variable **vars;
124 /* Constants (0 or more). */
126 const struct variable **const_vars;
127 union value *const_values;
131 struct freq **entries;
134 /* Column values, number of columns. */
138 /* Row values, number of rows. */
142 /* Number of statistically interesting columns/rows
143 (columns/rows with data in them). */
144 int ns_cols, ns_rows;
146 /* Matrix contents. */
147 double *mat; /* Matrix proper. */
148 double *row_tot; /* Row totals. */
149 double *col_tot; /* Column totals. */
150 double total; /* Grand total. */
153 /* Integer mode variable info. */
156 struct hmap_node hmap_node; /* In struct crosstabs_proc var_ranges map. */
157 const struct variable *var; /* The variable. */
158 int min; /* Minimum value. */
159 int max; /* Maximum value + 1. */
160 int count; /* max - min. */
163 struct crosstabs_proc
165 const struct dictionary *dict;
166 enum { INTEGER, GENERAL } mode;
167 enum mv_class exclude;
171 struct fmt_spec weight_format;
173 /* Variables specifies on VARIABLES. */
174 const struct variable **variables;
176 struct hmap var_ranges;
179 struct crosstabulation *pivots;
183 int n_cells; /* Number of cells requested. */
184 unsigned int cells; /* Bit k is 1 if cell k is requested. */
185 int a_cells[CRS_CL_count]; /* 0...n_cells-1 are the requested cells. */
187 /* Rounding of cells. */
188 bool round_case_weights; /* Round case weights? */
189 bool round_cells; /* If !round_case_weights, round cells? */
190 bool round_down; /* Round down? (otherwise to nearest) */
193 unsigned int statistics; /* Bit k is 1 if statistic k is requested. */
195 bool descending; /* True if descending sort order is requested. */
198 const struct var_range *get_var_range (const struct crosstabs_proc *,
199 const struct variable *);
201 static bool should_tabulate_case (const struct crosstabulation *,
202 const struct ccase *, enum mv_class exclude);
203 static void tabulate_general_case (struct crosstabulation *, const struct ccase *,
205 static void tabulate_integer_case (struct crosstabulation *, const struct ccase *,
207 static void postcalc (struct crosstabs_proc *);
208 static void submit (struct crosstabulation *, struct tab_table *);
211 round_weight (const struct crosstabs_proc *proc, double weight)
213 return proc->round_down ? floor (weight) : floor (weight + 0.5);
216 /* Parses and executes the CROSSTABS procedure. */
218 cmd_crosstabs (struct lexer *lexer, struct dataset *ds)
220 struct var_range *range, *next_range;
221 struct crosstabs_proc proc;
222 struct casegrouper *grouper;
223 struct casereader *input, *group;
224 struct cmd_crosstabs cmd;
225 struct crosstabulation *xt;
230 proc.dict = dataset_dict (ds);
231 proc.bad_warn = true;
232 proc.variables = NULL;
233 proc.n_variables = 0;
234 hmap_init (&proc.var_ranges);
237 proc.descending = false;
238 proc.weight_format = *dict_get_weight_format (dataset_dict (ds));
240 if (!parse_crosstabs (lexer, ds, &cmd, &proc))
242 result = CMD_FAILURE;
246 proc.mode = proc.n_variables ? INTEGER : GENERAL;
247 proc.barchart = cmd.sbc_barchart > 0;
249 proc.descending = cmd.val == CRS_DVALUE;
251 proc.round_case_weights = cmd.sbc_count && cmd.roundwhat == CRS_CASE;
252 proc.round_cells = cmd.sbc_count && cmd.roundwhat == CRS_CELL;
253 proc.round_down = cmd.roundhow == CRS_TRUNCATE;
257 proc.cells = 1u << CRS_CL_COUNT;
258 else if (cmd.a_cells[CRS_CL_ALL])
259 proc.cells = UINT_MAX;
263 for (i = 0; i < CRS_CL_count; i++)
265 proc.cells |= 1u << i;
267 proc.cells = ((1u << CRS_CL_COUNT)
269 | (1u << CRS_CL_COLUMN)
270 | (1u << CRS_CL_TOTAL));
272 proc.cells &= ((1u << CRS_CL_count) - 1);
273 proc.cells &= ~((1u << CRS_CL_NONE) | (1u << CRS_CL_ALL));
275 for (i = 0; i < CRS_CL_count; i++)
276 if (proc.cells & (1u << i))
277 proc.a_cells[proc.n_cells++] = i;
280 if (cmd.a_statistics[CRS_ST_ALL])
281 proc.statistics = UINT_MAX;
282 else if (cmd.sbc_statistics)
287 for (i = 0; i < CRS_ST_count; i++)
288 if (cmd.a_statistics[i])
289 proc.statistics |= 1u << i;
290 if (proc.statistics == 0)
291 proc.statistics |= 1u << CRS_ST_CHISQ;
297 proc.exclude = (cmd.miss == CRS_TABLE ? MV_ANY
298 : cmd.miss == CRS_INCLUDE ? MV_SYSTEM
300 if (proc.mode == GENERAL && proc.exclude == MV_NEVER)
302 msg (SE, _("Missing mode %s not allowed in general mode. "
303 "Assuming %s."), "REPORT", "MISSING=TABLE");
304 proc.exclude = MV_ANY;
308 proc.pivot = cmd.pivot == CRS_PIVOT;
310 input = casereader_create_filter_weight (proc_open (ds), dataset_dict (ds),
312 grouper = casegrouper_create_splits (input, dataset_dict (ds));
313 while (casegrouper_get_next_group (grouper, &group))
317 /* Output SPLIT FILE variables. */
318 c = casereader_peek (group, 0);
321 output_split_file_values (ds, c);
325 /* Initialize hash tables. */
326 for (xt = &proc.pivots[0]; xt < &proc.pivots[proc.n_pivots]; xt++)
327 hmap_init (&xt->data);
330 for (; (c = casereader_read (group)) != NULL; case_unref (c))
331 for (xt = &proc.pivots[0]; xt < &proc.pivots[proc.n_pivots]; xt++)
333 double weight = dict_get_case_weight (dataset_dict (ds), c,
335 if (cmd.roundwhat == CRS_CASE)
337 weight = round_weight (&proc, weight);
341 if (should_tabulate_case (xt, c, proc.exclude))
343 if (proc.mode == GENERAL)
344 tabulate_general_case (xt, c, weight);
346 tabulate_integer_case (xt, c, weight);
349 xt->missing += weight;
351 casereader_destroy (group);
356 ok = casegrouper_destroy (grouper);
357 ok = proc_commit (ds) && ok;
359 result = ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
362 free (proc.variables);
363 HMAP_FOR_EACH_SAFE (range, next_range, struct var_range, hmap_node,
366 hmap_delete (&proc.var_ranges, &range->hmap_node);
369 for (xt = &proc.pivots[0]; xt < &proc.pivots[proc.n_pivots]; xt++)
372 free (xt->const_vars);
373 /* We must not call value_destroy on const_values because
374 it is a wild pointer; it never pointed to anything owned
375 by the crosstabulation.
377 The rest of the data was allocated and destroyed at a
378 lower level already. */
385 /* Parses the TABLES subcommand. */
387 crs_custom_tables (struct lexer *lexer, struct dataset *ds,
388 struct cmd_crosstabs *cmd UNUSED, void *proc_)
390 struct crosstabs_proc *proc = proc_;
391 struct const_var_set *var_set;
393 const struct variable ***by = NULL;
395 size_t *by_nvar = NULL;
400 /* Ensure that this is a TABLES subcommand. */
401 if (!lex_match_id (lexer, "TABLES")
402 && (lex_token (lexer) != T_ID ||
403 dict_lookup_var (dataset_dict (ds), lex_tokcstr (lexer)) == NULL)
404 && lex_token (lexer) != T_ALL)
406 lex_match (lexer, T_EQUALS);
408 if (proc->variables != NULL)
409 var_set = const_var_set_create_from_array (proc->variables,
412 var_set = const_var_set_create_from_dict (dataset_dict (ds));
413 assert (var_set != NULL);
417 by = xnrealloc (by, n_by + 1, sizeof *by);
418 by_nvar = xnrealloc (by_nvar, n_by + 1, sizeof *by_nvar);
419 if (!parse_const_var_set_vars (lexer, var_set, &by[n_by], &by_nvar[n_by],
420 PV_NO_DUPLICATE | PV_NO_SCRATCH))
422 if (xalloc_oversized (nx, by_nvar[n_by]))
424 msg (SE, _("Too many cross-tabulation variables or dimensions."));
430 if (!lex_match (lexer, T_BY))
439 by_iter = xcalloc (n_by, sizeof *by_iter);
440 proc->pivots = xnrealloc (proc->pivots,
441 proc->n_pivots + nx, sizeof *proc->pivots);
442 for (i = 0; i < nx; i++)
444 struct crosstabulation *xt = &proc->pivots[proc->n_pivots++];
448 xt->weight_format = proc->weight_format;
451 xt->vars = xmalloc (n_by * sizeof *xt->vars);
453 xt->const_vars = NULL;
454 xt->const_values = NULL;
456 for (j = 0; j < n_by; j++)
457 xt->vars[j] = by[j][by_iter[j]];
459 for (j = n_by - 1; j >= 0; j--)
461 if (++by_iter[j] < by_nvar[j])
470 /* All return paths lead here. */
471 for (i = 0; i < n_by; i++)
476 const_var_set_destroy (var_set);
481 /* Parses the VARIABLES subcommand. */
483 crs_custom_variables (struct lexer *lexer, struct dataset *ds,
484 struct cmd_crosstabs *cmd UNUSED, void *proc_)
486 struct crosstabs_proc *proc = proc_;
489 msg (SE, _("%s must be specified before %s."), "VARIABLES", "TABLES");
493 lex_match (lexer, T_EQUALS);
497 size_t orig_nv = proc->n_variables;
502 if (!parse_variables_const (lexer, dataset_dict (ds),
503 &proc->variables, &proc->n_variables,
504 (PV_APPEND | PV_NUMERIC
505 | PV_NO_DUPLICATE | PV_NO_SCRATCH)))
508 if (!lex_force_match (lexer, T_LPAREN))
511 if (!lex_force_int (lexer))
513 min = lex_integer (lexer);
516 lex_match (lexer, T_COMMA);
518 if (!lex_force_int (lexer))
520 max = lex_integer (lexer);
523 msg (SE, _("Maximum value (%ld) less than minimum value (%ld)."),
529 if (!lex_force_match (lexer, T_RPAREN))
532 for (i = orig_nv; i < proc->n_variables; i++)
534 const struct variable *var = proc->variables[i];
535 struct var_range *vr = xmalloc (sizeof *vr);
540 vr->count = max - min + 1;
541 hmap_insert (&proc->var_ranges, &vr->hmap_node,
542 hash_pointer (var, 0));
545 if (lex_token (lexer) == T_SLASH)
552 free (proc->variables);
553 proc->variables = NULL;
554 proc->n_variables = 0;
558 /* Data file processing. */
560 const struct var_range *
561 get_var_range (const struct crosstabs_proc *proc, const struct variable *var)
563 if (!hmap_is_empty (&proc->var_ranges))
565 const struct var_range *range;
567 HMAP_FOR_EACH_IN_BUCKET (range, struct var_range, hmap_node,
568 hash_pointer (var, 0), &proc->var_ranges)
569 if (range->var == var)
577 should_tabulate_case (const struct crosstabulation *xt, const struct ccase *c,
578 enum mv_class exclude)
581 for (j = 0; j < xt->n_vars; j++)
583 const struct variable *var = xt->vars[j];
584 const struct var_range *range = get_var_range (xt->proc, var);
586 if (var_is_value_missing (var, case_data (c, var), exclude))
591 double num = case_num (c, var);
592 if (num < range->min || num >= range->max + 1.)
600 tabulate_integer_case (struct crosstabulation *xt, const struct ccase *c,
608 for (j = 0; j < xt->n_vars; j++)
610 /* Throw away fractional parts of values. */
611 hash = hash_int (case_num (c, xt->vars[j]), hash);
614 HMAP_FOR_EACH_WITH_HASH (te, struct freq, node, hash, &xt->data)
616 for (j = 0; j < xt->n_vars; j++)
617 if ((int) case_num (c, xt->vars[j]) != (int) te->values[j].f)
620 /* Found an existing entry. */
627 /* No existing entry. Create a new one. */
628 te = xmalloc (table_entry_size (xt->n_vars));
630 for (j = 0; j < xt->n_vars; j++)
631 te->values[j].f = (int) case_num (c, xt->vars[j]);
632 hmap_insert (&xt->data, &te->node, hash);
636 tabulate_general_case (struct crosstabulation *xt, const struct ccase *c,
644 for (j = 0; j < xt->n_vars; j++)
646 const struct variable *var = xt->vars[j];
647 hash = value_hash (case_data (c, var), var_get_width (var), hash);
650 HMAP_FOR_EACH_WITH_HASH (te, struct freq, node, hash, &xt->data)
652 for (j = 0; j < xt->n_vars; j++)
654 const struct variable *var = xt->vars[j];
655 if (!value_equal (case_data (c, var), &te->values[j],
656 var_get_width (var)))
660 /* Found an existing entry. */
667 /* No existing entry. Create a new one. */
668 te = xmalloc (table_entry_size (xt->n_vars));
670 for (j = 0; j < xt->n_vars; j++)
672 const struct variable *var = xt->vars[j];
673 value_clone (&te->values[j], case_data (c, var), var_get_width (var));
675 hmap_insert (&xt->data, &te->node, hash);
678 /* Post-data reading calculations. */
680 static int compare_table_entry_vars_3way (const struct freq *a,
681 const struct freq *b,
682 const struct crosstabulation *xt,
684 static int compare_table_entry_3way (const void *ap_, const void *bp_,
686 static int compare_table_entry_3way_inv (const void *ap_, const void *bp_,
689 static void enum_var_values (const struct crosstabulation *, int var_idx,
690 union value **valuesp, int *n_values,
692 static void output_crosstabulation (struct crosstabs_proc *,
693 struct crosstabulation *);
694 static void make_crosstabulation_subset (struct crosstabulation *xt,
695 size_t row0, size_t row1,
696 struct crosstabulation *subset);
697 static void make_summary_table (struct crosstabs_proc *);
698 static bool find_crosstab (struct crosstabulation *, size_t *row0p,
702 postcalc (struct crosstabs_proc *proc)
705 /* Round hash table entries, if requested
707 If this causes any of the cell counts to fall to zero, delete those
709 if (proc->round_cells)
710 for (struct crosstabulation *xt = proc->pivots;
711 xt < &proc->pivots[proc->n_pivots]; xt++)
713 struct freq *e, *next;
714 HMAP_FOR_EACH_SAFE (e, next, struct freq, node, &xt->data)
716 e->count = round_weight (proc, e->count);
719 hmap_delete (&xt->data, &e->node);
725 /* Convert hash tables into sorted arrays of entries. */
726 for (struct crosstabulation *xt = proc->pivots;
727 xt < &proc->pivots[proc->n_pivots]; xt++)
731 xt->n_entries = hmap_count (&xt->data);
732 xt->entries = xnmalloc (xt->n_entries, sizeof *xt->entries);
734 HMAP_FOR_EACH (e, struct freq, node, &xt->data)
735 xt->entries[i++] = e;
736 hmap_destroy (&xt->data);
738 sort (xt->entries, xt->n_entries, sizeof *xt->entries,
739 proc->descending ? compare_table_entry_3way_inv : compare_table_entry_3way,
744 make_summary_table (proc);
746 /* Output each pivot table. */
747 for (struct crosstabulation *xt = proc->pivots;
748 xt < &proc->pivots[proc->n_pivots]; xt++)
750 if (proc->pivot || xt->n_vars == 2)
751 output_crosstabulation (proc, xt);
754 size_t row0 = 0, row1 = 0;
755 while (find_crosstab (xt, &row0, &row1))
757 struct crosstabulation subset;
758 make_crosstabulation_subset (xt, row0, row1, &subset);
759 output_crosstabulation (proc, &subset);
764 (barchart_create (xt->vars, xt->n_vars, _("Count"), false, xt->entries, xt->n_entries));
767 /* Free output and prepare for next split file. */
768 for (struct crosstabulation *xt = proc->pivots;
769 xt < &proc->pivots[proc->n_pivots]; xt++)
773 /* Free the members that were allocated in this function(and the values
774 owned by the entries.
776 The other pointer members are either both allocated and destroyed at a
777 lower level (in output_crosstabulation), or both allocated and
778 destroyed at a higher level (in crs_custom_tables and free_proc,
780 for (size_t i = 0; i < xt->n_vars; i++)
782 int width = var_get_width (xt->vars[i]);
783 if (value_needs_init (width))
787 for (j = 0; j < xt->n_entries; j++)
788 value_destroy (&xt->entries[j]->values[i], width);
792 for (size_t i = 0; i < xt->n_entries; i++)
793 free (xt->entries[i]);
799 make_crosstabulation_subset (struct crosstabulation *xt, size_t row0,
800 size_t row1, struct crosstabulation *subset)
805 assert (xt->n_consts == 0);
806 subset->missing = xt->missing;
808 subset->vars = xt->vars;
809 subset->n_consts = xt->n_vars - 2;
810 subset->const_vars = xt->vars + 2;
811 subset->const_values = &xt->entries[row0]->values[2];
813 subset->entries = &xt->entries[row0];
814 subset->n_entries = row1 - row0;
818 compare_table_entry_var_3way (const struct freq *a,
819 const struct freq *b,
820 const struct crosstabulation *xt,
823 return value_compare_3way (&a->values[idx], &b->values[idx],
824 var_get_width (xt->vars[idx]));
828 compare_table_entry_vars_3way (const struct freq *a,
829 const struct freq *b,
830 const struct crosstabulation *xt,
835 for (i = idx1 - 1; i >= idx0; i--)
837 int cmp = compare_table_entry_var_3way (a, b, xt, i);
844 /* Compare the struct freq at *AP to the one at *BP and
845 return a strcmp()-type result. */
847 compare_table_entry_3way (const void *ap_, const void *bp_, const void *xt_)
849 const struct freq *const *ap = ap_;
850 const struct freq *const *bp = bp_;
851 const struct freq *a = *ap;
852 const struct freq *b = *bp;
853 const struct crosstabulation *xt = xt_;
856 cmp = compare_table_entry_vars_3way (a, b, xt, 2, xt->n_vars);
860 cmp = compare_table_entry_var_3way (a, b, xt, ROW_VAR);
864 return compare_table_entry_var_3way (a, b, xt, COL_VAR);
867 /* Inverted version of compare_table_entry_3way */
869 compare_table_entry_3way_inv (const void *ap_, const void *bp_, const void *xt_)
871 return -compare_table_entry_3way (ap_, bp_, xt_);
875 find_first_difference (const struct crosstabulation *xt, size_t row)
878 return xt->n_vars - 1;
881 const struct freq *a = xt->entries[row];
882 const struct freq *b = xt->entries[row - 1];
885 for (col = xt->n_vars - 1; col >= 0; col--)
886 if (compare_table_entry_var_3way (a, b, xt, col))
892 /* Output a table summarizing the cases processed. */
894 make_summary_table (struct crosstabs_proc *proc)
896 struct tab_table *summary;
897 struct crosstabulation *xt;
901 summary = tab_create (7, 3 + proc->n_pivots);
902 tab_set_format (summary, RC_WEIGHT, &proc->weight_format);
903 tab_title (summary, _("Summary."));
904 tab_headers (summary, 1, 0, 3, 0);
905 tab_joint_text (summary, 1, 0, 6, 0, TAB_CENTER, _("Cases"));
906 tab_joint_text (summary, 1, 1, 2, 1, TAB_CENTER, _("Valid"));
907 tab_joint_text (summary, 3, 1, 4, 1, TAB_CENTER, _("Missing"));
908 tab_joint_text (summary, 5, 1, 6, 1, TAB_CENTER, _("Total"));
909 tab_hline (summary, TAL_1, 1, 6, 1);
910 tab_hline (summary, TAL_1, 1, 6, 2);
911 tab_vline (summary, TAL_1, 3, 1, 1);
912 tab_vline (summary, TAL_1, 5, 1, 1);
913 for (i = 0; i < 3; i++)
915 tab_text (summary, 1 + i * 2, 2, TAB_RIGHT, _("N"));
916 tab_text (summary, 2 + i * 2, 2, TAB_RIGHT, _("Percent"));
918 tab_offset (summary, 0, 3);
920 ds_init_empty (&name);
921 for (xt = &proc->pivots[0]; xt < &proc->pivots[proc->n_pivots]; xt++)
927 tab_hline (summary, TAL_1, 0, 6, 0);
930 for (i = 0; i < xt->n_vars; i++)
933 ds_put_cstr (&name, " * ");
934 ds_put_cstr (&name, var_to_string (xt->vars[i]));
936 tab_text (summary, 0, 0, TAB_LEFT, ds_cstr (&name));
939 for (i = 0; i < xt->n_entries; i++)
940 valid += xt->entries[i]->count;
945 for (i = 0; i < 3; i++)
947 tab_double (summary, i * 2 + 1, 0, TAB_RIGHT, n[i], NULL, RC_WEIGHT);
948 tab_text_format (summary, i * 2 + 2, 0, TAB_RIGHT, "%.1f%%",
952 tab_next_row (summary);
956 submit (NULL, summary);
961 static struct tab_table *create_crosstab_table (struct crosstabs_proc *,
962 struct crosstabulation *);
963 static struct tab_table *create_chisq_table (struct crosstabs_proc *proc, struct crosstabulation *);
964 static struct tab_table *create_sym_table (struct crosstabs_proc *proc, struct crosstabulation *);
965 static struct tab_table *create_risk_table (struct crosstabs_proc *proc, struct crosstabulation *);
966 static struct tab_table *create_direct_table (struct crosstabs_proc *proc, struct crosstabulation *);
967 static void display_dimensions (struct crosstabs_proc *, struct crosstabulation *,
968 struct tab_table *, int first_difference);
969 static void display_crosstabulation (struct crosstabs_proc *,
970 struct crosstabulation *,
972 static void display_chisq (struct crosstabulation *, struct tab_table *,
973 bool *showed_fisher);
974 static void display_symmetric (struct crosstabs_proc *, struct crosstabulation *,
976 static void display_risk (struct crosstabulation *, struct tab_table *);
977 static void display_directional (struct crosstabs_proc *, struct crosstabulation *,
979 static void table_value_missing (struct crosstabs_proc *proc,
980 struct tab_table *table, int c, int r,
981 unsigned char opt, const union value *v,
982 const struct variable *var);
983 static void delete_missing (struct crosstabulation *);
984 static void build_matrix (struct crosstabulation *);
986 /* Output pivot table XT in the context of PROC. */
988 output_crosstabulation (struct crosstabs_proc *proc, struct crosstabulation *xt)
990 struct tab_table *table = NULL; /* Crosstabulation table. */
991 struct tab_table *chisq = NULL; /* Chi-square table. */
992 bool showed_fisher = false;
993 struct tab_table *sym = NULL; /* Symmetric measures table. */
994 struct tab_table *risk = NULL; /* Risk estimate table. */
995 struct tab_table *direct = NULL; /* Directional measures table. */
998 enum_var_values (xt, COL_VAR, &xt->cols, &xt->n_cols, proc->descending);
1000 if (xt->n_cols == 0)
1005 ds_init_cstr (&vars, var_to_string (xt->vars[0]));
1006 for (i = 1; i < xt->n_vars; i++)
1007 ds_put_format (&vars, " * %s", var_to_string (xt->vars[i]));
1009 /* TRANSLATORS: The %s here describes a crosstabulation. It takes the
1010 form "var1 * var2 * var3 * ...". */
1011 msg (SW, _("Crosstabulation %s contained no non-missing cases."),
1020 table = create_crosstab_table (proc, xt);
1021 if (proc->statistics & (1u << CRS_ST_CHISQ))
1022 chisq = create_chisq_table (proc, xt);
1023 if (proc->statistics & ((1u << CRS_ST_PHI) | (1u << CRS_ST_CC)
1024 | (1u << CRS_ST_BTAU) | (1u << CRS_ST_CTAU)
1025 | (1u << CRS_ST_GAMMA) | (1u << CRS_ST_CORR)
1026 | (1u << CRS_ST_KAPPA)))
1027 sym = create_sym_table (proc, xt);
1028 if (proc->statistics & (1u << CRS_ST_RISK))
1029 risk = create_risk_table (proc, xt);
1030 if (proc->statistics & ((1u << CRS_ST_LAMBDA) | (1u << CRS_ST_UC)
1031 | (1u << CRS_ST_D) | (1u << CRS_ST_ETA)))
1032 direct = create_direct_table (proc, xt);
1035 while (find_crosstab (xt, &row0, &row1))
1037 struct crosstabulation x;
1038 int first_difference;
1040 make_crosstabulation_subset (xt, row0, row1, &x);
1042 /* Find all the row variable values. */
1043 enum_var_values (&x, ROW_VAR, &x.rows, &x.n_rows, proc->descending);
1045 if (size_overflow_p (xtimes (xtimes (x.n_rows, x.n_cols),
1048 x.row_tot = xmalloc (x.n_rows * sizeof *x.row_tot);
1049 x.col_tot = xmalloc (x.n_cols * sizeof *x.col_tot);
1050 x.mat = xmalloc (x.n_rows * x.n_cols * sizeof *x.mat);
1052 /* Allocate table space for the matrix. */
1054 && tab_row (table) + (x.n_rows + 1) * proc->n_cells > tab_nr (table))
1055 tab_realloc (table, -1,
1056 MAX (tab_nr (table) + (x.n_rows + 1) * proc->n_cells,
1057 tab_nr (table) * xt->n_entries / x.n_entries));
1061 /* Find the first variable that differs from the last subtable. */
1062 first_difference = find_first_difference (xt, row0);
1065 display_dimensions (proc, &x, table, first_difference);
1066 display_crosstabulation (proc, &x, table);
1069 if (proc->exclude == MV_NEVER)
1070 delete_missing (&x);
1074 display_dimensions (proc, &x, chisq, first_difference);
1075 display_chisq (&x, chisq, &showed_fisher);
1079 display_dimensions (proc, &x, sym, first_difference);
1080 display_symmetric (proc, &x, sym);
1084 display_dimensions (proc, &x, risk, first_difference);
1085 display_risk (&x, risk);
1089 display_dimensions (proc, &x, direct, first_difference);
1090 display_directional (proc, &x, direct);
1093 /* Free the parts of x that are not owned by xt. In
1094 particular we must not free x.cols, which is the same as
1095 xt->cols, which is freed at the end of this function. */
1103 submit (NULL, table);
1108 tab_resize (chisq, 4 + (xt->n_vars - 2), -1);
1114 submit (xt, direct);
1120 build_matrix (struct crosstabulation *x)
1122 const int col_var_width = var_get_width (x->vars[COL_VAR]);
1123 const int row_var_width = var_get_width (x->vars[ROW_VAR]);
1130 for (p = x->entries; p < &x->entries[x->n_entries]; p++)
1132 const struct freq *te = *p;
1134 while (!value_equal (&x->rows[row], &te->values[ROW_VAR], row_var_width))
1136 for (; col < x->n_cols; col++)
1142 while (!value_equal (&x->cols[col], &te->values[COL_VAR], col_var_width))
1149 if (++col >= x->n_cols)
1155 while (mp < &x->mat[x->n_cols * x->n_rows])
1157 assert (mp == &x->mat[x->n_cols * x->n_rows]);
1159 /* Column totals, row totals, ns_rows. */
1161 for (col = 0; col < x->n_cols; col++)
1162 x->col_tot[col] = 0.0;
1163 for (row = 0; row < x->n_rows; row++)
1164 x->row_tot[row] = 0.0;
1166 for (row = 0; row < x->n_rows; row++)
1168 bool row_is_empty = true;
1169 for (col = 0; col < x->n_cols; col++)
1173 row_is_empty = false;
1174 x->col_tot[col] += *mp;
1175 x->row_tot[row] += *mp;
1182 assert (mp == &x->mat[x->n_cols * x->n_rows]);
1186 for (col = 0; col < x->n_cols; col++)
1187 for (row = 0; row < x->n_rows; row++)
1188 if (x->mat[col + row * x->n_cols] != 0.0)
1196 for (col = 0; col < x->n_cols; col++)
1197 x->total += x->col_tot[col];
1200 static struct tab_table *
1201 create_crosstab_table (struct crosstabs_proc *proc, struct crosstabulation *xt)
1208 static const struct tuple names[] =
1210 {CRS_CL_COUNT, N_("count")},
1211 {CRS_CL_ROW, N_("row %")},
1212 {CRS_CL_COLUMN, N_("column %")},
1213 {CRS_CL_TOTAL, N_("total %")},
1214 {CRS_CL_EXPECTED, N_("expected")},
1215 {CRS_CL_RESIDUAL, N_("residual")},
1216 {CRS_CL_SRESIDUAL, N_("std. resid.")},
1217 {CRS_CL_ASRESIDUAL, N_("adj. resid.")},
1219 const int n_names = sizeof names / sizeof *names;
1220 const struct tuple *t;
1222 struct tab_table *table;
1223 struct string title;
1224 struct crosstabulation x;
1228 make_crosstabulation_subset (xt, 0, 0, &x);
1230 table = tab_create (x.n_consts + 1 + x.n_cols + 1,
1231 (x.n_entries / x.n_cols) * 3 / 2 * proc->n_cells + 10);
1232 tab_headers (table, x.n_consts + 1, 0, 2, 0);
1233 tab_set_format (table, RC_WEIGHT, &proc->weight_format);
1235 /* First header line. */
1236 tab_joint_text (table, x.n_consts + 1, 0,
1237 (x.n_consts + 1) + (x.n_cols - 1), 0,
1238 TAB_CENTER | TAT_TITLE, var_to_string (x.vars[COL_VAR]));
1240 tab_hline (table, TAL_1, x.n_consts + 1,
1241 x.n_consts + 2 + x.n_cols - 2, 1);
1243 /* Second header line. */
1244 for (i = 2; i < x.n_consts + 2; i++)
1245 tab_joint_text (table, x.n_consts + 2 - i - 1, 0,
1246 x.n_consts + 2 - i - 1, 1,
1247 TAB_RIGHT | TAT_TITLE, var_to_string (x.vars[i]));
1248 tab_text (table, x.n_consts + 2 - 2, 1, TAB_RIGHT | TAT_TITLE,
1249 var_to_string (x.vars[ROW_VAR]));
1250 for (i = 0; i < x.n_cols; i++)
1251 table_value_missing (proc, table, x.n_consts + 2 + i - 1, 1, TAB_RIGHT,
1252 &x.cols[i], x.vars[COL_VAR]);
1253 tab_text (table, x.n_consts + 2 + x.n_cols - 1, 1, TAB_CENTER, _("Total"));
1255 tab_hline (table, TAL_1, 0, x.n_consts + 2 + x.n_cols - 1, 2);
1256 tab_vline (table, TAL_1, x.n_consts + 2 + x.n_cols - 1, 0, 1);
1259 ds_init_empty (&title);
1260 for (i = 0; i < x.n_consts + 2; i++)
1263 ds_put_cstr (&title, " * ");
1264 ds_put_cstr (&title, var_to_string (x.vars[i]));
1266 for (i = 0; i < xt->n_consts; i++)
1268 const struct variable *var = xt->const_vars[i];
1271 ds_put_format (&title, ", %s=", var_to_string (var));
1273 /* Insert the formatted value of VAR without any leading spaces. */
1274 s = data_out (&xt->const_values[i], var_get_encoding (var),
1275 var_get_print_format (var));
1276 ds_put_cstr (&title, s + strspn (s, " "));
1280 ds_put_cstr (&title, " [");
1282 for (t = names; t < &names[n_names]; t++)
1283 if (proc->cells & (1u << t->value))
1286 ds_put_cstr (&title, ", ");
1287 ds_put_cstr (&title, gettext (t->name));
1289 ds_put_cstr (&title, "].");
1291 tab_title (table, "%s", ds_cstr (&title));
1292 ds_destroy (&title);
1294 tab_offset (table, 0, 2);
1298 static struct tab_table *
1299 create_chisq_table (struct crosstabs_proc *proc, struct crosstabulation *xt)
1301 struct tab_table *chisq;
1303 chisq = tab_create (6 + (xt->n_vars - 2),
1304 xt->n_entries / xt->n_cols * 3 / 2 * N_CHISQ + 10);
1305 tab_headers (chisq, 1 + (xt->n_vars - 2), 0, 1, 0);
1306 tab_set_format (chisq, RC_WEIGHT, &proc->weight_format);
1308 tab_title (chisq, _("Chi-square tests."));
1310 tab_offset (chisq, xt->n_vars - 2, 0);
1311 tab_text (chisq, 0, 0, TAB_LEFT | TAT_TITLE, _("Statistic"));
1312 tab_text (chisq, 1, 0, TAB_RIGHT | TAT_TITLE, _("Value"));
1313 tab_text (chisq, 2, 0, TAB_RIGHT | TAT_TITLE, _("df"));
1314 tab_text (chisq, 3, 0, TAB_RIGHT | TAT_TITLE,
1315 _("Asymp. Sig. (2-tailed)"));
1316 tab_text_format (chisq, 4, 0, TAB_RIGHT | TAT_TITLE,
1317 _("Exact Sig. (%d-tailed)"), 2);
1318 tab_text_format (chisq, 5, 0, TAB_RIGHT | TAT_TITLE,
1319 _("Exact Sig. (%d-tailed)"), 1);
1320 tab_offset (chisq, 0, 1);
1325 /* Symmetric measures. */
1326 static struct tab_table *
1327 create_sym_table (struct crosstabs_proc *proc, struct crosstabulation *xt)
1329 struct tab_table *sym;
1331 sym = tab_create (6 + (xt->n_vars - 2),
1332 xt->n_entries / xt->n_cols * 7 + 10);
1334 tab_set_format (sym, RC_WEIGHT, &proc->weight_format);
1336 tab_headers (sym, 2 + (xt->n_vars - 2), 0, 1, 0);
1337 tab_title (sym, _("Symmetric measures."));
1339 tab_offset (sym, xt->n_vars - 2, 0);
1340 tab_text (sym, 0, 0, TAB_LEFT | TAT_TITLE, _("Category"));
1341 tab_text (sym, 1, 0, TAB_LEFT | TAT_TITLE, _("Statistic"));
1342 tab_text (sym, 2, 0, TAB_RIGHT | TAT_TITLE, _("Value"));
1343 tab_text (sym, 3, 0, TAB_RIGHT | TAT_TITLE, _("Asymp. Std. Error"));
1344 tab_text (sym, 4, 0, TAB_RIGHT | TAT_TITLE, _("Approx. T"));
1345 tab_text (sym, 5, 0, TAB_RIGHT | TAT_TITLE, _("Approx. Sig."));
1346 tab_offset (sym, 0, 1);
1351 /* Risk estimate. */
1352 static struct tab_table *
1353 create_risk_table (struct crosstabs_proc *proc, struct crosstabulation *xt)
1355 struct tab_table *risk;
1357 risk = tab_create (4 + (xt->n_vars - 2), xt->n_entries / xt->n_cols * 4 + 10);
1358 tab_headers (risk, 1 + xt->n_vars - 2, 0, 2, 0);
1359 tab_title (risk, _("Risk estimate."));
1360 tab_set_format (risk, RC_WEIGHT, &proc->weight_format);
1362 tab_offset (risk, xt->n_vars - 2, 0);
1363 tab_joint_text_format (risk, 2, 0, 3, 0, TAB_CENTER | TAT_TITLE,
1364 _("95%% Confidence Interval"));
1365 tab_text (risk, 0, 1, TAB_LEFT | TAT_TITLE, _("Statistic"));
1366 tab_text (risk, 1, 1, TAB_RIGHT | TAT_TITLE, _("Value"));
1367 tab_text (risk, 2, 1, TAB_RIGHT | TAT_TITLE, _("Lower"));
1368 tab_text (risk, 3, 1, TAB_RIGHT | TAT_TITLE, _("Upper"));
1369 tab_hline (risk, TAL_1, 2, 3, 1);
1370 tab_vline (risk, TAL_1, 2, 0, 1);
1371 tab_offset (risk, 0, 2);
1376 /* Directional measures. */
1377 static struct tab_table *
1378 create_direct_table (struct crosstabs_proc *proc, struct crosstabulation *xt)
1380 struct tab_table *direct;
1382 direct = tab_create (7 + (xt->n_vars - 2),
1383 xt->n_entries / xt->n_cols * 7 + 10);
1384 tab_headers (direct, 3 + (xt->n_vars - 2), 0, 1, 0);
1385 tab_title (direct, _("Directional measures."));
1386 tab_set_format (direct, RC_WEIGHT, &proc->weight_format);
1388 tab_offset (direct, xt->n_vars - 2, 0);
1389 tab_text (direct, 0, 0, TAB_LEFT | TAT_TITLE, _("Category"));
1390 tab_text (direct, 1, 0, TAB_LEFT | TAT_TITLE, _("Statistic"));
1391 tab_text (direct, 2, 0, TAB_LEFT | TAT_TITLE, _("Type"));
1392 tab_text (direct, 3, 0, TAB_RIGHT | TAT_TITLE, _("Value"));
1393 tab_text (direct, 4, 0, TAB_RIGHT | TAT_TITLE, _("Asymp. Std. Error"));
1394 tab_text (direct, 5, 0, TAB_RIGHT | TAT_TITLE, _("Approx. T"));
1395 tab_text (direct, 6, 0, TAB_RIGHT | TAT_TITLE, _("Approx. Sig."));
1396 tab_offset (direct, 0, 1);
1402 /* Delete missing rows and columns for statistical analysis when
1405 delete_missing (struct crosstabulation *xt)
1409 for (r = 0; r < xt->n_rows; r++)
1410 if (var_is_num_missing (xt->vars[ROW_VAR], xt->rows[r].f, MV_USER))
1412 for (c = 0; c < xt->n_cols; c++)
1413 xt->mat[c + r * xt->n_cols] = 0.;
1418 for (c = 0; c < xt->n_cols; c++)
1419 if (var_is_num_missing (xt->vars[COL_VAR], xt->cols[c].f, MV_USER))
1421 for (r = 0; r < xt->n_rows; r++)
1422 xt->mat[c + r * xt->n_cols] = 0.;
1427 /* Prepare table T for submission, and submit it. */
1429 submit (struct crosstabulation *xt, struct tab_table *t)
1436 tab_resize (t, -1, 0);
1437 if (tab_nr (t) == tab_t (t))
1439 table_unref (&t->table);
1442 tab_offset (t, 0, 0);
1444 for (i = 2; i < xt->n_vars; i++)
1445 tab_text (t, xt->n_vars - i - 1, 0, TAB_RIGHT | TAT_TITLE,
1446 var_to_string (xt->vars[i]));
1447 tab_box (t, TAL_2, TAL_2, -1, -1, 0, 0, tab_nc (t) - 1, tab_nr (t) - 1);
1448 tab_box (t, -1, -1, -1, TAL_1, tab_l (t), tab_t (t) - 1, tab_nc (t) - 1,
1450 tab_vline (t, TAL_2, tab_l (t), 0, tab_nr (t) - 1);
1456 find_crosstab (struct crosstabulation *xt, size_t *row0p, size_t *row1p)
1458 size_t row0 = *row1p;
1461 if (row0 >= xt->n_entries)
1464 for (row1 = row0 + 1; row1 < xt->n_entries; row1++)
1466 struct freq *a = xt->entries[row0];
1467 struct freq *b = xt->entries[row1];
1468 if (compare_table_entry_vars_3way (a, b, xt, 2, xt->n_vars) != 0)
1476 /* Compares `union value's A_ and B_ and returns a strcmp()-like
1477 result. WIDTH_ points to an int which is either 0 for a
1478 numeric value or a string width for a string value. */
1480 compare_value_3way (const void *a_, const void *b_, const void *width_)
1482 const union value *a = a_;
1483 const union value *b = b_;
1484 const int *width = width_;
1486 return value_compare_3way (a, b, *width);
1489 /* Inverted version of the above */
1491 compare_value_3way_inv (const void *a_, const void *b_, const void *width_)
1493 return -compare_value_3way (a_, b_, width_);
1497 /* Given an array of ENTRY_CNT table_entry structures starting at
1498 ENTRIES, creates a sorted list of the values that the variable
1499 with index VAR_IDX takes on. The values are returned as a
1500 malloc()'d array stored in *VALUES, with the number of values
1501 stored in *VALUE_CNT.
1503 The caller must eventually free *VALUES, but each pointer in *VALUES points
1504 to existing data not owned by *VALUES itself. */
1506 enum_var_values (const struct crosstabulation *xt, int var_idx,
1507 union value **valuesp, int *n_values, bool descending)
1509 const struct variable *var = xt->vars[var_idx];
1510 const struct var_range *range = get_var_range (xt->proc, var);
1511 union value *values;
1516 values = *valuesp = xnmalloc (range->count, sizeof *values);
1517 *n_values = range->count;
1518 for (i = 0; i < range->count; i++)
1519 values[i].f = range->min + i;
1523 int width = var_get_width (var);
1524 struct hmapx_node *node;
1525 const union value *iter;
1529 for (i = 0; i < xt->n_entries; i++)
1531 const struct freq *te = xt->entries[i];
1532 const union value *value = &te->values[var_idx];
1533 size_t hash = value_hash (value, width, 0);
1535 HMAPX_FOR_EACH_WITH_HASH (iter, node, hash, &set)
1536 if (value_equal (iter, value, width))
1539 hmapx_insert (&set, (union value *) value, hash);
1544 *n_values = hmapx_count (&set);
1545 values = *valuesp = xnmalloc (*n_values, sizeof *values);
1547 HMAPX_FOR_EACH (iter, node, &set)
1548 values[i++] = *iter;
1549 hmapx_destroy (&set);
1551 sort (values, *n_values, sizeof *values,
1552 descending ? compare_value_3way_inv : compare_value_3way,
1557 /* Sets cell (C,R) in TABLE, with options OPT, to have a value taken
1558 from V, displayed with print format spec from variable VAR. When
1559 in REPORT missing-value mode, missing values have an M appended. */
1561 table_value_missing (struct crosstabs_proc *proc,
1562 struct tab_table *table, int c, int r, unsigned char opt,
1563 const union value *v, const struct variable *var)
1565 const char *label = var_lookup_value_label (var, v);
1567 tab_text (table, c, r, TAB_LEFT, label);
1570 const struct fmt_spec *print = var_get_print_format (var);
1571 if (proc->exclude == MV_NEVER && var_is_value_missing (var, v, MV_USER))
1573 char *s = data_out (v, dict_get_encoding (proc->dict), print);
1574 tab_text_format (table, c, r, opt, "%sM", s + strspn (s, " "));
1578 tab_value (table, c, r, opt, v, var, print);
1582 /* Draws a line across TABLE at the current row to indicate the most
1583 major dimension variable with index FIRST_DIFFERENCE out of N_VARS
1584 that changed, and puts the values that changed into the table. TB
1585 and XT must be the corresponding table_entry and crosstab,
1588 display_dimensions (struct crosstabs_proc *proc, struct crosstabulation *xt,
1589 struct tab_table *table, int first_difference)
1591 tab_hline (table, TAL_1, xt->n_consts + xt->n_vars - first_difference - 1, tab_nc (table) - 1, 0);
1593 for (; first_difference >= 2; first_difference--)
1594 table_value_missing (proc, table, xt->n_consts + xt->n_vars - first_difference - 1, 0,
1595 TAB_RIGHT, &xt->entries[0]->values[first_difference],
1596 xt->vars[first_difference]);
1599 /* Put VALUE into cell (C,R) of TABLE, suffixed with character
1600 SUFFIX if nonzero. If MARK_MISSING is true the entry is
1601 additionally suffixed with a letter `M'. */
1603 format_cell_entry (struct tab_table *table, int c, int r, double value,
1604 char suffix, bool mark_missing, const struct dictionary *dict)
1612 s = data_out (&v, dict_get_encoding (dict), settings_get_format ());
1616 suffixes[suffix_len++] = suffix;
1618 suffixes[suffix_len++] = 'M';
1619 suffixes[suffix_len] = '\0';
1621 tab_text_format (table, c, r, TAB_RIGHT, "%s%s",
1622 s + strspn (s, " "), suffixes);
1627 /* Displays the crosstabulation table. */
1629 display_crosstabulation (struct crosstabs_proc *proc,
1630 struct crosstabulation *xt, struct tab_table *table)
1636 for (r = 0; r < xt->n_rows; r++)
1637 table_value_missing (proc, table, xt->n_consts + xt->n_vars - 2,
1638 r * proc->n_cells, TAB_RIGHT, &xt->rows[r],
1641 tab_text (table, xt->n_vars - 2, xt->n_rows * proc->n_cells,
1642 TAB_LEFT, _("Total"));
1644 /* Put in the actual cells. */
1646 tab_offset (table, xt->n_consts + xt->n_vars - 1, -1);
1647 for (r = 0; r < xt->n_rows; r++)
1649 if (proc->n_cells > 1)
1650 tab_hline (table, TAL_1, -1, xt->n_cols, 0);
1651 for (c = 0; c < xt->n_cols; c++)
1653 bool mark_missing = false;
1654 double expected_value = xt->row_tot[r] * xt->col_tot[c] / xt->total;
1655 if (proc->exclude == MV_NEVER
1656 && (var_is_num_missing (xt->vars[COL_VAR], xt->cols[c].f, MV_USER)
1657 || var_is_num_missing (xt->vars[ROW_VAR], xt->rows[r].f,
1659 mark_missing = true;
1660 for (i = 0; i < proc->n_cells; i++)
1665 switch (proc->a_cells[i])
1671 v = *mp / xt->row_tot[r] * 100.;
1675 v = *mp / xt->col_tot[c] * 100.;
1679 v = *mp / xt->total * 100.;
1682 case CRS_CL_EXPECTED:
1685 case CRS_CL_RESIDUAL:
1686 v = *mp - expected_value;
1688 case CRS_CL_SRESIDUAL:
1689 v = (*mp - expected_value) / sqrt (expected_value);
1691 case CRS_CL_ASRESIDUAL:
1692 v = ((*mp - expected_value)
1693 / sqrt (expected_value
1694 * (1. - xt->row_tot[r] / xt->total)
1695 * (1. - xt->col_tot[c] / xt->total)));
1700 format_cell_entry (table, c, i, v, suffix, mark_missing, proc->dict);
1706 tab_offset (table, -1, tab_row (table) + proc->n_cells);
1710 tab_offset (table, -1, tab_row (table) - proc->n_cells * xt->n_rows);
1711 for (r = 0; r < xt->n_rows; r++)
1713 bool mark_missing = false;
1715 if (proc->exclude == MV_NEVER
1716 && var_is_num_missing (xt->vars[ROW_VAR], xt->rows[r].f, MV_USER))
1717 mark_missing = true;
1719 for (i = 0; i < proc->n_cells; i++)
1724 switch (proc->a_cells[i])
1734 v = xt->row_tot[r] / xt->total * 100.;
1738 v = xt->row_tot[r] / xt->total * 100.;
1741 case CRS_CL_EXPECTED:
1742 case CRS_CL_RESIDUAL:
1743 case CRS_CL_SRESIDUAL:
1744 case CRS_CL_ASRESIDUAL:
1751 format_cell_entry (table, xt->n_cols, 0, v, suffix, mark_missing, proc->dict);
1752 tab_next_row (table);
1756 /* Column totals, grand total. */
1758 if (proc->n_cells > 1)
1759 tab_hline (table, TAL_1, -1, xt->n_cols, 0);
1760 for (c = 0; c <= xt->n_cols; c++)
1762 double ct = c < xt->n_cols ? xt->col_tot[c] : xt->total;
1763 bool mark_missing = false;
1766 if (proc->exclude == MV_NEVER && c < xt->n_cols
1767 && var_is_num_missing (xt->vars[COL_VAR], xt->cols[c].f, MV_USER))
1768 mark_missing = true;
1770 for (i = 0; i < proc->n_cells; i++)
1775 switch (proc->a_cells[i])
1781 v = ct / xt->total * 100.;
1789 v = ct / xt->total * 100.;
1792 case CRS_CL_EXPECTED:
1793 case CRS_CL_RESIDUAL:
1794 case CRS_CL_SRESIDUAL:
1795 case CRS_CL_ASRESIDUAL:
1801 format_cell_entry (table, c, i, v, suffix, mark_missing, proc->dict);
1806 tab_offset (table, -1, tab_row (table) + last_row);
1807 tab_offset (table, 0, -1);
1810 static void calc_r (struct crosstabulation *,
1811 double *XT, double *Y, double *, double *, double *);
1812 static void calc_chisq (struct crosstabulation *,
1813 double[N_CHISQ], int[N_CHISQ], double *, double *);
1815 /* Display chi-square statistics. */
1817 display_chisq (struct crosstabulation *xt, struct tab_table *chisq,
1818 bool *showed_fisher)
1820 static const char *chisq_stats[N_CHISQ] =
1822 N_("Pearson Chi-Square"),
1823 N_("Likelihood Ratio"),
1824 N_("Fisher's Exact Test"),
1825 N_("Continuity Correction"),
1826 N_("Linear-by-Linear Association"),
1828 double chisq_v[N_CHISQ];
1829 double fisher1, fisher2;
1834 calc_chisq (xt, chisq_v, df, &fisher1, &fisher2);
1836 tab_offset (chisq, xt->n_consts + xt->n_vars - 2, -1);
1838 for (i = 0; i < N_CHISQ; i++)
1840 if ((i != 2 && chisq_v[i] == SYSMIS)
1841 || (i == 2 && fisher1 == SYSMIS))
1844 tab_text (chisq, 0, 0, TAB_LEFT, gettext (chisq_stats[i]));
1847 tab_double (chisq, 1, 0, TAB_RIGHT, chisq_v[i], NULL, RC_OTHER);
1848 tab_double (chisq, 2, 0, TAB_RIGHT, df[i], NULL, RC_WEIGHT);
1849 tab_double (chisq, 3, 0, TAB_RIGHT,
1850 gsl_cdf_chisq_Q (chisq_v[i], df[i]), NULL, RC_PVALUE);
1854 *showed_fisher = true;
1855 tab_double (chisq, 4, 0, TAB_RIGHT, fisher2, NULL, RC_PVALUE);
1856 tab_double (chisq, 5, 0, TAB_RIGHT, fisher1, NULL, RC_PVALUE);
1858 tab_next_row (chisq);
1861 tab_text (chisq, 0, 0, TAB_LEFT, _("N of Valid Cases"));
1862 tab_double (chisq, 1, 0, TAB_RIGHT, xt->total, NULL, RC_WEIGHT);
1863 tab_next_row (chisq);
1865 tab_offset (chisq, 0, -1);
1868 static int calc_symmetric (struct crosstabs_proc *, struct crosstabulation *,
1869 double[N_SYMMETRIC], double[N_SYMMETRIC],
1870 double[N_SYMMETRIC],
1871 double[3], double[3], double[3]);
1873 /* Display symmetric measures. */
1875 display_symmetric (struct crosstabs_proc *proc, struct crosstabulation *xt,
1876 struct tab_table *sym)
1878 static const char *categories[] =
1880 N_("Nominal by Nominal"),
1881 N_("Ordinal by Ordinal"),
1882 N_("Interval by Interval"),
1883 N_("Measure of Agreement"),
1886 static const char *stats[N_SYMMETRIC] =
1890 N_("Contingency Coefficient"),
1891 N_("Kendall's tau-b"),
1892 N_("Kendall's tau-c"),
1894 N_("Spearman Correlation"),
1899 static const int stats_categories[N_SYMMETRIC] =
1901 0, 0, 0, 1, 1, 1, 1, 2, 3,
1905 double sym_v[N_SYMMETRIC], sym_ase[N_SYMMETRIC], sym_t[N_SYMMETRIC];
1906 double somers_d_v[3], somers_d_ase[3], somers_d_t[3];
1909 if (!calc_symmetric (proc, xt, sym_v, sym_ase, sym_t,
1910 somers_d_v, somers_d_ase, somers_d_t))
1913 tab_offset (sym, xt->n_consts + xt->n_vars - 2, -1);
1915 for (i = 0; i < N_SYMMETRIC; i++)
1917 if (sym_v[i] == SYSMIS)
1920 if (stats_categories[i] != last_cat)
1922 last_cat = stats_categories[i];
1923 tab_text (sym, 0, 0, TAB_LEFT, gettext (categories[last_cat]));
1926 tab_text (sym, 1, 0, TAB_LEFT, gettext (stats[i]));
1927 tab_double (sym, 2, 0, TAB_RIGHT, sym_v[i], NULL, RC_OTHER);
1928 if (sym_ase[i] != SYSMIS)
1929 tab_double (sym, 3, 0, TAB_RIGHT, sym_ase[i], NULL, RC_OTHER);
1930 if (sym_t[i] != SYSMIS)
1931 tab_double (sym, 4, 0, TAB_RIGHT, sym_t[i], NULL, RC_OTHER);
1932 /*tab_double (sym, 5, 0, TAB_RIGHT, normal_sig (sym_v[i]), NULL, RC_PVALUE);*/
1936 tab_text (sym, 0, 0, TAB_LEFT, _("N of Valid Cases"));
1937 tab_double (sym, 2, 0, TAB_RIGHT, xt->total, NULL, RC_WEIGHT);
1940 tab_offset (sym, 0, -1);
1943 static int calc_risk (struct crosstabulation *,
1944 double[], double[], double[], union value *);
1946 /* Display risk estimate. */
1948 display_risk (struct crosstabulation *xt, struct tab_table *risk)
1951 double risk_v[3], lower[3], upper[3];
1955 if (!calc_risk (xt, risk_v, upper, lower, c))
1958 tab_offset (risk, xt->n_consts + xt->n_vars - 2, -1);
1960 for (i = 0; i < 3; i++)
1962 const struct variable *cv = xt->vars[COL_VAR];
1963 const struct variable *rv = xt->vars[ROW_VAR];
1964 int cvw = var_get_width (cv);
1965 int rvw = var_get_width (rv);
1967 if (risk_v[i] == SYSMIS)
1973 if (var_is_numeric (cv))
1974 sprintf (buf, _("Odds Ratio for %s (%g / %g)"),
1975 var_to_string (cv), c[0].f, c[1].f);
1977 sprintf (buf, _("Odds Ratio for %s (%.*s / %.*s)"),
1979 cvw, value_str (&c[0], cvw),
1980 cvw, value_str (&c[1], cvw));
1984 if (var_is_numeric (rv))
1985 sprintf (buf, _("For cohort %s = %.*g"),
1986 var_to_string (rv), DBL_DIG + 1, xt->rows[i - 1].f);
1988 sprintf (buf, _("For cohort %s = %.*s"),
1990 rvw, value_str (&xt->rows[i - 1], rvw));
1994 tab_text (risk, 0, 0, TAB_LEFT, buf);
1995 tab_double (risk, 1, 0, TAB_RIGHT, risk_v[i], NULL, RC_OTHER);
1996 tab_double (risk, 2, 0, TAB_RIGHT, lower[i], NULL, RC_OTHER);
1997 tab_double (risk, 3, 0, TAB_RIGHT, upper[i], NULL, RC_OTHER);
1998 tab_next_row (risk);
2001 tab_text (risk, 0, 0, TAB_LEFT, _("N of Valid Cases"));
2002 tab_double (risk, 1, 0, TAB_RIGHT, xt->total, NULL, RC_WEIGHT);
2003 tab_next_row (risk);
2005 tab_offset (risk, 0, -1);
2008 static int calc_directional (struct crosstabs_proc *, struct crosstabulation *,
2009 double[N_DIRECTIONAL], double[N_DIRECTIONAL],
2010 double[N_DIRECTIONAL], double[N_DIRECTIONAL]);
2012 /* Display directional measures. */
2014 display_directional (struct crosstabs_proc *proc, struct crosstabulation *xt,
2015 struct tab_table *direct)
2017 static const char *categories[] =
2019 N_("Nominal by Nominal"),
2020 N_("Ordinal by Ordinal"),
2021 N_("Nominal by Interval"),
2024 static const char *stats[] =
2027 N_("Goodman and Kruskal tau"),
2028 N_("Uncertainty Coefficient"),
2033 static const char *types[] =
2040 static const int stats_categories[N_DIRECTIONAL] =
2042 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2,
2045 static const int stats_stats[N_DIRECTIONAL] =
2047 0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4,
2050 static const int stats_types[N_DIRECTIONAL] =
2052 0, 1, 2, 1, 2, 0, 1, 2, 0, 1, 2, 1, 2,
2055 static const int *stats_lookup[] =
2062 static const char **stats_names[] =
2074 double direct_v[N_DIRECTIONAL];
2075 double direct_ase[N_DIRECTIONAL];
2076 double direct_t[N_DIRECTIONAL];
2077 double sig[N_DIRECTIONAL];
2081 if (!calc_directional (proc, xt, direct_v, direct_ase, direct_t, sig))
2084 tab_offset (direct, xt->n_consts + xt->n_vars - 2, -1);
2086 for (i = 0; i < N_DIRECTIONAL; i++)
2088 if (direct_v[i] == SYSMIS)
2094 for (j = 0; j < 3; j++)
2095 if (last[j] != stats_lookup[j][i])
2098 tab_hline (direct, TAL_1, j, 6, 0);
2103 int k = last[j] = stats_lookup[j][i];
2108 string = var_to_string (xt->vars[0]);
2110 string = var_to_string (xt->vars[1]);
2112 tab_text_format (direct, j, 0, TAB_LEFT,
2113 gettext (stats_names[j][k]), string);
2118 tab_double (direct, 3, 0, TAB_RIGHT, direct_v[i], NULL, RC_OTHER);
2119 if (direct_ase[i] != SYSMIS)
2120 tab_double (direct, 4, 0, TAB_RIGHT, direct_ase[i], NULL, RC_OTHER);
2121 if (direct_t[i] != SYSMIS)
2122 tab_double (direct, 5, 0, TAB_RIGHT, direct_t[i], NULL, RC_OTHER);
2123 tab_double (direct, 6, 0, TAB_RIGHT, sig[i], NULL, RC_PVALUE);
2124 tab_next_row (direct);
2127 tab_offset (direct, 0, -1);
2130 /* Statistical calculations. */
2132 /* Returns the value of the logarithm of gamma (factorial) function for an integer
2135 log_gamma_int (double xt)
2140 for (i = 2; i < xt; i++)
2146 /* Calculate P_r as specified in _SPSS Statistical Algorithms_,
2148 static inline double
2149 Pr (int a, int b, int c, int d)
2151 return exp (log_gamma_int (a + b + 1.) - log_gamma_int (a + 1.)
2152 + log_gamma_int (c + d + 1.) - log_gamma_int (b + 1.)
2153 + log_gamma_int (a + c + 1.) - log_gamma_int (c + 1.)
2154 + log_gamma_int (b + d + 1.) - log_gamma_int (d + 1.)
2155 - log_gamma_int (a + b + c + d + 1.));
2158 /* Swap the contents of A and B. */
2160 swap (int *a, int *b)
2167 /* Calculate significance for Fisher's exact test as specified in
2168 _SPSS Statistical Algorithms_, Appendix 5. */
2170 calc_fisher (int a, int b, int c, int d, double *fisher1, double *fisher2)
2175 if (MIN (c, d) < MIN (a, b))
2176 swap (&a, &c), swap (&b, &d);
2177 if (MIN (b, d) < MIN (a, c))
2178 swap (&a, &b), swap (&c, &d);
2182 swap (&a, &b), swap (&c, &d);
2184 swap (&a, &c), swap (&b, &d);
2187 pn1 = Pr (a, b, c, d);
2189 for (xt = 1; xt <= a; xt++)
2191 *fisher1 += Pr (a - xt, b + xt, c + xt, d - xt);
2194 *fisher2 = *fisher1;
2196 for (xt = 1; xt <= b; xt++)
2198 double p = Pr (a + xt, b - xt, c - xt, d + xt);
2204 /* Calculates chi-squares into CHISQ. MAT is a matrix with N_COLS
2205 columns with values COLS and N_ROWS rows with values ROWS. Values
2206 in the matrix sum to xt->total. */
2208 calc_chisq (struct crosstabulation *xt,
2209 double chisq[N_CHISQ], int df[N_CHISQ],
2210 double *fisher1, double *fisher2)
2214 chisq[0] = chisq[1] = 0.;
2215 chisq[2] = chisq[3] = chisq[4] = SYSMIS;
2216 *fisher1 = *fisher2 = SYSMIS;
2218 df[0] = df[1] = (xt->ns_cols - 1) * (xt->ns_rows - 1);
2220 if (xt->ns_rows <= 1 || xt->ns_cols <= 1)
2222 chisq[0] = chisq[1] = SYSMIS;
2226 for (r = 0; r < xt->n_rows; r++)
2227 for (c = 0; c < xt->n_cols; c++)
2229 const double expected = xt->row_tot[r] * xt->col_tot[c] / xt->total;
2230 const double freq = xt->mat[xt->n_cols * r + c];
2231 const double residual = freq - expected;
2233 chisq[0] += residual * residual / expected;
2235 chisq[1] += freq * log (expected / freq);
2246 /* Calculate Yates and Fisher exact test. */
2247 if (xt->ns_cols == 2 && xt->ns_rows == 2)
2249 double f11, f12, f21, f22;
2255 for (i = j = 0; i < xt->n_cols; i++)
2256 if (xt->col_tot[i] != 0.)
2265 f11 = xt->mat[nz_cols[0]];
2266 f12 = xt->mat[nz_cols[1]];
2267 f21 = xt->mat[nz_cols[0] + xt->n_cols];
2268 f22 = xt->mat[nz_cols[1] + xt->n_cols];
2273 const double xt_ = fabs (f11 * f22 - f12 * f21) - 0.5 * xt->total;
2276 chisq[3] = (xt->total * pow2 (xt_)
2277 / (f11 + f12) / (f21 + f22)
2278 / (f11 + f21) / (f12 + f22));
2286 calc_fisher (f11 + .5, f12 + .5, f21 + .5, f22 + .5, fisher1, fisher2);
2289 /* Calculate Mantel-Haenszel. */
2290 if (var_is_numeric (xt->vars[ROW_VAR]) && var_is_numeric (xt->vars[COL_VAR]))
2292 double r, ase_0, ase_1;
2293 calc_r (xt, (double *) xt->rows, (double *) xt->cols, &r, &ase_0, &ase_1);
2295 chisq[4] = (xt->total - 1.) * r * r;
2300 /* Calculate the value of Pearson's r. r is stored into R, its T value into
2301 T, and standard error into ERROR. The row and column values must be
2302 passed in XT and Y. */
2304 calc_r (struct crosstabulation *xt,
2305 double *XT, double *Y, double *r, double *t, double *error)
2307 double SX, SY, S, T;
2309 double sum_XYf, sum_X2Y2f;
2310 double sum_Xr, sum_X2r;
2311 double sum_Yc, sum_Y2c;
2314 for (sum_X2Y2f = sum_XYf = 0., i = 0; i < xt->n_rows; i++)
2315 for (j = 0; j < xt->n_cols; j++)
2317 double fij = xt->mat[j + i * xt->n_cols];
2318 double product = XT[i] * Y[j];
2319 double temp = fij * product;
2321 sum_X2Y2f += temp * product;
2324 for (sum_Xr = sum_X2r = 0., i = 0; i < xt->n_rows; i++)
2326 sum_Xr += XT[i] * xt->row_tot[i];
2327 sum_X2r += pow2 (XT[i]) * xt->row_tot[i];
2329 Xbar = sum_Xr / xt->total;
2331 for (sum_Yc = sum_Y2c = 0., i = 0; i < xt->n_cols; i++)
2333 sum_Yc += Y[i] * xt->col_tot[i];
2334 sum_Y2c += Y[i] * Y[i] * xt->col_tot[i];
2336 Ybar = sum_Yc / xt->total;
2338 S = sum_XYf - sum_Xr * sum_Yc / xt->total;
2339 SX = sum_X2r - pow2 (sum_Xr) / xt->total;
2340 SY = sum_Y2c - pow2 (sum_Yc) / xt->total;
2343 *t = *r / sqrt (1 - pow2 (*r)) * sqrt (xt->total - 2);
2348 for (s = c = 0., i = 0; i < xt->n_rows; i++)
2349 for (j = 0; j < xt->n_cols; j++)
2351 double Xresid, Yresid;
2354 Xresid = XT[i] - Xbar;
2355 Yresid = Y[j] - Ybar;
2356 temp = (T * Xresid * Yresid
2358 * (Xresid * Xresid * SY + Yresid * Yresid * SX)));
2359 y = xt->mat[j + i * xt->n_cols] * temp * temp - c;
2364 *error = sqrt (s) / (T * T);
2368 /* Calculate symmetric statistics and their asymptotic standard
2369 errors. Returns 0 if none could be calculated. */
2371 calc_symmetric (struct crosstabs_proc *proc, struct crosstabulation *xt,
2372 double v[N_SYMMETRIC], double ase[N_SYMMETRIC],
2373 double t[N_SYMMETRIC],
2374 double somers_d_v[3], double somers_d_ase[3],
2375 double somers_d_t[3])
2379 q = MIN (xt->ns_rows, xt->ns_cols);
2383 for (i = 0; i < N_SYMMETRIC; i++)
2384 v[i] = ase[i] = t[i] = SYSMIS;
2386 /* Phi, Cramer's V, contingency coefficient. */
2387 if (proc->statistics & ((1u << CRS_ST_PHI) | (1u << CRS_ST_CC)))
2389 double Xp = 0.; /* Pearson chi-square. */
2392 for (r = 0; r < xt->n_rows; r++)
2393 for (c = 0; c < xt->n_cols; c++)
2395 const double expected = xt->row_tot[r] * xt->col_tot[c] / xt->total;
2396 const double freq = xt->mat[xt->n_cols * r + c];
2397 const double residual = freq - expected;
2399 Xp += residual * residual / expected;
2402 if (proc->statistics & (1u << CRS_ST_PHI))
2404 v[0] = sqrt (Xp / xt->total);
2405 v[1] = sqrt (Xp / (xt->total * (q - 1)));
2407 if (proc->statistics & (1u << CRS_ST_CC))
2408 v[2] = sqrt (Xp / (Xp + xt->total));
2411 if (proc->statistics & ((1u << CRS_ST_BTAU) | (1u << CRS_ST_CTAU)
2412 | (1u << CRS_ST_GAMMA) | (1u << CRS_ST_D)))
2417 double btau_cum, ctau_cum, gamma_cum, d_yx_cum, d_xy_cum;
2421 Dr = Dc = pow2 (xt->total);
2422 for (r = 0; r < xt->n_rows; r++)
2423 Dr -= pow2 (xt->row_tot[r]);
2424 for (c = 0; c < xt->n_cols; c++)
2425 Dc -= pow2 (xt->col_tot[c]);
2427 cum = xnmalloc (xt->n_cols * xt->n_rows, sizeof *cum);
2428 for (c = 0; c < xt->n_cols; c++)
2432 for (r = 0; r < xt->n_rows; r++)
2433 cum[c + r * xt->n_cols] = ct += xt->mat[c + r * xt->n_cols];
2442 for (i = 0; i < xt->n_rows; i++)
2446 for (j = 1; j < xt->n_cols; j++)
2447 Cij += xt->col_tot[j] - cum[j + i * xt->n_cols];
2450 for (j = 1; j < xt->n_cols; j++)
2451 Dij += cum[j + (i - 1) * xt->n_cols];
2455 double fij = xt->mat[j + i * xt->n_cols];
2459 if (++j == xt->n_cols)
2461 assert (j < xt->n_cols);
2463 Cij -= xt->col_tot[j] - cum[j + i * xt->n_cols];
2464 Dij += xt->col_tot[j - 1] - cum[j - 1 + i * xt->n_cols];
2468 Cij += cum[j - 1 + (i - 1) * xt->n_cols];
2469 Dij -= cum[j + (i - 1) * xt->n_cols];
2475 if (proc->statistics & (1u << CRS_ST_BTAU))
2476 v[3] = (P - Q) / sqrt (Dr * Dc);
2477 if (proc->statistics & (1u << CRS_ST_CTAU))
2478 v[4] = (q * (P - Q)) / (pow2 (xt->total) * (q - 1));
2479 if (proc->statistics & (1u << CRS_ST_GAMMA))
2480 v[5] = (P - Q) / (P + Q);
2482 /* ASE for tau-b, tau-c, gamma. Calculations could be
2483 eliminated here, at expense of memory. */
2488 btau_cum = ctau_cum = gamma_cum = d_yx_cum = d_xy_cum = 0.;
2489 for (i = 0; i < xt->n_rows; i++)
2493 for (j = 1; j < xt->n_cols; j++)
2494 Cij += xt->col_tot[j] - cum[j + i * xt->n_cols];
2497 for (j = 1; j < xt->n_cols; j++)
2498 Dij += cum[j + (i - 1) * xt->n_cols];
2502 double fij = xt->mat[j + i * xt->n_cols];
2504 if (proc->statistics & (1u << CRS_ST_BTAU))
2506 const double temp = (2. * sqrt (Dr * Dc) * (Cij - Dij)
2507 + v[3] * (xt->row_tot[i] * Dc
2508 + xt->col_tot[j] * Dr));
2509 btau_cum += fij * temp * temp;
2513 const double temp = Cij - Dij;
2514 ctau_cum += fij * temp * temp;
2517 if (proc->statistics & (1u << CRS_ST_GAMMA))
2519 const double temp = Q * Cij - P * Dij;
2520 gamma_cum += fij * temp * temp;
2523 if (proc->statistics & (1u << CRS_ST_D))
2525 d_yx_cum += fij * pow2 (Dr * (Cij - Dij)
2526 - (P - Q) * (xt->total - xt->row_tot[i]));
2527 d_xy_cum += fij * pow2 (Dc * (Dij - Cij)
2528 - (Q - P) * (xt->total - xt->col_tot[j]));
2531 if (++j == xt->n_cols)
2533 assert (j < xt->n_cols);
2535 Cij -= xt->col_tot[j] - cum[j + i * xt->n_cols];
2536 Dij += xt->col_tot[j - 1] - cum[j - 1 + i * xt->n_cols];
2540 Cij += cum[j - 1 + (i - 1) * xt->n_cols];
2541 Dij -= cum[j + (i - 1) * xt->n_cols];
2547 btau_var = ((btau_cum
2548 - (xt->total * pow2 (xt->total * (P - Q) / sqrt (Dr * Dc) * (Dr + Dc))))
2550 if (proc->statistics & (1u << CRS_ST_BTAU))
2552 ase[3] = sqrt (btau_var);
2553 t[3] = v[3] / (2 * sqrt ((ctau_cum - (P - Q) * (P - Q) / xt->total)
2556 if (proc->statistics & (1u << CRS_ST_CTAU))
2558 ase[4] = ((2 * q / ((q - 1) * pow2 (xt->total)))
2559 * sqrt (ctau_cum - (P - Q) * (P - Q) / xt->total));
2560 t[4] = v[4] / ase[4];
2562 if (proc->statistics & (1u << CRS_ST_GAMMA))
2564 ase[5] = ((4. / ((P + Q) * (P + Q))) * sqrt (gamma_cum));
2565 t[5] = v[5] / (2. / (P + Q)
2566 * sqrt (ctau_cum - (P - Q) * (P - Q) / xt->total));
2568 if (proc->statistics & (1u << CRS_ST_D))
2570 somers_d_v[0] = (P - Q) / (.5 * (Dc + Dr));
2571 somers_d_ase[0] = SYSMIS;
2572 somers_d_t[0] = (somers_d_v[0]
2574 * sqrt (ctau_cum - pow2 (P - Q) / xt->total)));
2575 somers_d_v[1] = (P - Q) / Dc;
2576 somers_d_ase[1] = 2. / pow2 (Dc) * sqrt (d_xy_cum);
2577 somers_d_t[1] = (somers_d_v[1]
2579 * sqrt (ctau_cum - pow2 (P - Q) / xt->total)));
2580 somers_d_v[2] = (P - Q) / Dr;
2581 somers_d_ase[2] = 2. / pow2 (Dr) * sqrt (d_yx_cum);
2582 somers_d_t[2] = (somers_d_v[2]
2584 * sqrt (ctau_cum - pow2 (P - Q) / xt->total)));
2590 /* Spearman correlation, Pearson's r. */
2591 if (proc->statistics & (1u << CRS_ST_CORR))
2593 double *R = xmalloc (sizeof *R * xt->n_rows);
2594 double *C = xmalloc (sizeof *C * xt->n_cols);
2597 double y, t, c = 0., s = 0.;
2602 R[i] = s + (xt->row_tot[i] + 1.) / 2.;
2603 y = xt->row_tot[i] - c;
2607 if (++i == xt->n_rows)
2609 assert (i < xt->n_rows);
2614 double y, t, c = 0., s = 0.;
2619 C[j] = s + (xt->col_tot[j] + 1.) / 2;
2620 y = xt->col_tot[j] - c;
2624 if (++j == xt->n_cols)
2626 assert (j < xt->n_cols);
2630 calc_r (xt, R, C, &v[6], &t[6], &ase[6]);
2635 calc_r (xt, (double *) xt->rows, (double *) xt->cols, &v[7], &t[7], &ase[7]);
2638 /* Cohen's kappa. */
2639 if (proc->statistics & (1u << CRS_ST_KAPPA) && xt->ns_rows == xt->ns_cols)
2641 double ase_under_h0;
2642 double sum_fii, sum_rici, sum_fiiri_ci, sum_fijri_ci2, sum_riciri_ci;
2645 for (sum_fii = sum_rici = sum_fiiri_ci = sum_riciri_ci = 0., i = j = 0;
2646 i < xt->ns_rows; i++, j++)
2650 while (xt->col_tot[j] == 0.)
2653 prod = xt->row_tot[i] * xt->col_tot[j];
2654 sum = xt->row_tot[i] + xt->col_tot[j];
2656 sum_fii += xt->mat[j + i * xt->n_cols];
2658 sum_fiiri_ci += xt->mat[j + i * xt->n_cols] * sum;
2659 sum_riciri_ci += prod * sum;
2661 for (sum_fijri_ci2 = 0., i = 0; i < xt->ns_rows; i++)
2662 for (j = 0; j < xt->ns_cols; j++)
2664 double sum = xt->row_tot[i] + xt->col_tot[j];
2665 sum_fijri_ci2 += xt->mat[j + i * xt->n_cols] * sum * sum;
2668 v[8] = (xt->total * sum_fii - sum_rici) / (pow2 (xt->total) - sum_rici);
2670 ase_under_h0 = sqrt ((pow2 (xt->total) * sum_rici
2671 + sum_rici * sum_rici
2672 - xt->total * sum_riciri_ci)
2673 / (xt->total * (pow2 (xt->total) - sum_rici) * (pow2 (xt->total) - sum_rici)));
2675 ase[8] = sqrt (xt->total * (((sum_fii * (xt->total - sum_fii))
2676 / pow2 (pow2 (xt->total) - sum_rici))
2677 + ((2. * (xt->total - sum_fii)
2678 * (2. * sum_fii * sum_rici
2679 - xt->total * sum_fiiri_ci))
2680 / pow3 (pow2 (xt->total) - sum_rici))
2681 + (pow2 (xt->total - sum_fii)
2682 * (xt->total * sum_fijri_ci2 - 4.
2683 * sum_rici * sum_rici)
2684 / pow4 (pow2 (xt->total) - sum_rici))));
2686 t[8] = v[8] / ase_under_h0;
2692 /* Calculate risk estimate. */
2694 calc_risk (struct crosstabulation *xt,
2695 double *value, double *upper, double *lower, union value *c)
2697 double f11, f12, f21, f22;
2703 for (i = 0; i < 3; i++)
2704 value[i] = upper[i] = lower[i] = SYSMIS;
2707 if (xt->ns_rows != 2 || xt->ns_cols != 2)
2714 for (i = j = 0; i < xt->n_cols; i++)
2715 if (xt->col_tot[i] != 0.)
2724 f11 = xt->mat[nz_cols[0]];
2725 f12 = xt->mat[nz_cols[1]];
2726 f21 = xt->mat[nz_cols[0] + xt->n_cols];
2727 f22 = xt->mat[nz_cols[1] + xt->n_cols];
2729 c[0] = xt->cols[nz_cols[0]];
2730 c[1] = xt->cols[nz_cols[1]];
2733 value[0] = (f11 * f22) / (f12 * f21);
2734 v = sqrt (1. / f11 + 1. / f12 + 1. / f21 + 1. / f22);
2735 lower[0] = value[0] * exp (-1.960 * v);
2736 upper[0] = value[0] * exp (1.960 * v);
2738 value[1] = (f11 * (f21 + f22)) / (f21 * (f11 + f12));
2739 v = sqrt ((f12 / (f11 * (f11 + f12)))
2740 + (f22 / (f21 * (f21 + f22))));
2741 lower[1] = value[1] * exp (-1.960 * v);
2742 upper[1] = value[1] * exp (1.960 * v);
2744 value[2] = (f12 * (f21 + f22)) / (f22 * (f11 + f12));
2745 v = sqrt ((f11 / (f12 * (f11 + f12)))
2746 + (f21 / (f22 * (f21 + f22))));
2747 lower[2] = value[2] * exp (-1.960 * v);
2748 upper[2] = value[2] * exp (1.960 * v);
2753 /* Calculate directional measures. */
2755 calc_directional (struct crosstabs_proc *proc, struct crosstabulation *xt,
2756 double v[N_DIRECTIONAL], double ase[N_DIRECTIONAL],
2757 double t[N_DIRECTIONAL], double sig[N_DIRECTIONAL])
2762 for (i = 0; i < N_DIRECTIONAL; i++)
2763 v[i] = ase[i] = t[i] = sig[i] = SYSMIS;
2767 if (proc->statistics & (1u << CRS_ST_LAMBDA))
2769 double *fim = xnmalloc (xt->n_rows, sizeof *fim);
2770 int *fim_index = xnmalloc (xt->n_rows, sizeof *fim_index);
2771 double *fmj = xnmalloc (xt->n_cols, sizeof *fmj);
2772 int *fmj_index = xnmalloc (xt->n_cols, sizeof *fmj_index);
2773 double sum_fim, sum_fmj;
2775 int rm_index, cm_index;
2778 /* Find maximum for each row and their sum. */
2779 for (sum_fim = 0., i = 0; i < xt->n_rows; i++)
2781 double max = xt->mat[i * xt->n_cols];
2784 for (j = 1; j < xt->n_cols; j++)
2785 if (xt->mat[j + i * xt->n_cols] > max)
2787 max = xt->mat[j + i * xt->n_cols];
2791 sum_fim += fim[i] = max;
2792 fim_index[i] = index;
2795 /* Find maximum for each column. */
2796 for (sum_fmj = 0., j = 0; j < xt->n_cols; j++)
2798 double max = xt->mat[j];
2801 for (i = 1; i < xt->n_rows; i++)
2802 if (xt->mat[j + i * xt->n_cols] > max)
2804 max = xt->mat[j + i * xt->n_cols];
2808 sum_fmj += fmj[j] = max;
2809 fmj_index[j] = index;
2812 /* Find maximum row total. */
2813 rm = xt->row_tot[0];
2815 for (i = 1; i < xt->n_rows; i++)
2816 if (xt->row_tot[i] > rm)
2818 rm = xt->row_tot[i];
2822 /* Find maximum column total. */
2823 cm = xt->col_tot[0];
2825 for (j = 1; j < xt->n_cols; j++)
2826 if (xt->col_tot[j] > cm)
2828 cm = xt->col_tot[j];
2832 v[0] = (sum_fim + sum_fmj - cm - rm) / (2. * xt->total - rm - cm);
2833 v[1] = (sum_fmj - rm) / (xt->total - rm);
2834 v[2] = (sum_fim - cm) / (xt->total - cm);
2836 /* ASE1 for Y given XT. */
2841 for (i = 0; i < xt->n_rows; i++)
2842 if (cm_index == fim_index[i])
2844 ase[2] = sqrt ((xt->total - sum_fim) * (sum_fim + cm - 2. * accum)
2845 / pow3 (xt->total - cm));
2848 /* ASE0 for Y given XT. */
2852 for (accum = 0., i = 0; i < xt->n_rows; i++)
2853 if (cm_index != fim_index[i])
2854 accum += (xt->mat[i * xt->n_cols + fim_index[i]]
2855 + xt->mat[i * xt->n_cols + cm_index]);
2856 t[2] = v[2] / (sqrt (accum - pow2 (sum_fim - cm) / xt->total) / (xt->total - cm));
2859 /* ASE1 for XT given Y. */
2864 for (j = 0; j < xt->n_cols; j++)
2865 if (rm_index == fmj_index[j])
2867 ase[1] = sqrt ((xt->total - sum_fmj) * (sum_fmj + rm - 2. * accum)
2868 / pow3 (xt->total - rm));
2871 /* ASE0 for XT given Y. */
2875 for (accum = 0., j = 0; j < xt->n_cols; j++)
2876 if (rm_index != fmj_index[j])
2877 accum += (xt->mat[j + xt->n_cols * fmj_index[j]]
2878 + xt->mat[j + xt->n_cols * rm_index]);
2879 t[1] = v[1] / (sqrt (accum - pow2 (sum_fmj - rm) / xt->total) / (xt->total - rm));
2882 /* Symmetric ASE0 and ASE1. */
2887 for (accum0 = accum1 = 0., i = 0; i < xt->n_rows; i++)
2888 for (j = 0; j < xt->n_cols; j++)
2890 int temp0 = (fmj_index[j] == i) + (fim_index[i] == j);
2891 int temp1 = (i == rm_index) + (j == cm_index);
2892 accum0 += xt->mat[j + i * xt->n_cols] * pow2 (temp0 - temp1);
2893 accum1 += (xt->mat[j + i * xt->n_cols]
2894 * pow2 (temp0 + (v[0] - 1.) * temp1));
2896 ase[0] = sqrt (accum1 - 4. * xt->total * v[0] * v[0]) / (2. * xt->total - rm - cm);
2897 t[0] = v[0] / (sqrt (accum0 - pow2 (sum_fim + sum_fmj - cm - rm) / xt->total)
2898 / (2. * xt->total - rm - cm));
2901 for (i = 0; i < 3; i++)
2902 sig[i] = 2 * gsl_cdf_ugaussian_Q (t[i]);
2911 double sum_fij2_ri, sum_fij2_ci;
2912 double sum_ri2, sum_cj2;
2914 for (sum_fij2_ri = sum_fij2_ci = 0., i = 0; i < xt->n_rows; i++)
2915 for (j = 0; j < xt->n_cols; j++)
2917 double temp = pow2 (xt->mat[j + i * xt->n_cols]);
2918 sum_fij2_ri += temp / xt->row_tot[i];
2919 sum_fij2_ci += temp / xt->col_tot[j];
2922 for (sum_ri2 = 0., i = 0; i < xt->n_rows; i++)
2923 sum_ri2 += pow2 (xt->row_tot[i]);
2925 for (sum_cj2 = 0., j = 0; j < xt->n_cols; j++)
2926 sum_cj2 += pow2 (xt->col_tot[j]);
2928 v[3] = (xt->total * sum_fij2_ci - sum_ri2) / (pow2 (xt->total) - sum_ri2);
2929 v[4] = (xt->total * sum_fij2_ri - sum_cj2) / (pow2 (xt->total) - sum_cj2);
2933 if (proc->statistics & (1u << CRS_ST_UC))
2935 double UX, UY, UXY, P;
2936 double ase1_yx, ase1_xy, ase1_sym;
2939 for (UX = 0., i = 0; i < xt->n_rows; i++)
2940 if (xt->row_tot[i] > 0.)
2941 UX -= xt->row_tot[i] / xt->total * log (xt->row_tot[i] / xt->total);
2943 for (UY = 0., j = 0; j < xt->n_cols; j++)
2944 if (xt->col_tot[j] > 0.)
2945 UY -= xt->col_tot[j] / xt->total * log (xt->col_tot[j] / xt->total);
2947 for (UXY = P = 0., i = 0; i < xt->n_rows; i++)
2948 for (j = 0; j < xt->n_cols; j++)
2950 double entry = xt->mat[j + i * xt->n_cols];
2955 P += entry * pow2 (log (xt->col_tot[j] * xt->row_tot[i] / (xt->total * entry)));
2956 UXY -= entry / xt->total * log (entry / xt->total);
2959 for (ase1_yx = ase1_xy = ase1_sym = 0., i = 0; i < xt->n_rows; i++)
2960 for (j = 0; j < xt->n_cols; j++)
2962 double entry = xt->mat[j + i * xt->n_cols];
2967 ase1_yx += entry * pow2 (UY * log (entry / xt->row_tot[i])
2968 + (UX - UXY) * log (xt->col_tot[j] / xt->total));
2969 ase1_xy += entry * pow2 (UX * log (entry / xt->col_tot[j])
2970 + (UY - UXY) * log (xt->row_tot[i] / xt->total));
2971 ase1_sym += entry * pow2 ((UXY
2972 * log (xt->row_tot[i] * xt->col_tot[j] / pow2 (xt->total)))
2973 - (UX + UY) * log (entry / xt->total));
2976 v[5] = 2. * ((UX + UY - UXY) / (UX + UY));
2977 ase[5] = (2. / (xt->total * pow2 (UX + UY))) * sqrt (ase1_sym);
2980 v[6] = (UX + UY - UXY) / UX;
2981 ase[6] = sqrt (ase1_xy) / (xt->total * UX * UX);
2982 t[6] = v[6] / (sqrt (P - xt->total * pow2 (UX + UY - UXY)) / (xt->total * UX));
2984 v[7] = (UX + UY - UXY) / UY;
2985 ase[7] = sqrt (ase1_yx) / (xt->total * UY * UY);
2986 t[7] = v[7] / (sqrt (P - xt->total * pow2 (UX + UY - UXY)) / (xt->total * UY));
2990 if (proc->statistics & (1u << CRS_ST_D))
2992 double v_dummy[N_SYMMETRIC];
2993 double ase_dummy[N_SYMMETRIC];
2994 double t_dummy[N_SYMMETRIC];
2995 double somers_d_v[3];
2996 double somers_d_ase[3];
2997 double somers_d_t[3];
2999 if (calc_symmetric (proc, xt, v_dummy, ase_dummy, t_dummy,
3000 somers_d_v, somers_d_ase, somers_d_t))
3003 for (i = 0; i < 3; i++)
3005 v[8 + i] = somers_d_v[i];
3006 ase[8 + i] = somers_d_ase[i];
3007 t[8 + i] = somers_d_t[i];
3008 sig[8 + i] = 2 * gsl_cdf_ugaussian_Q (fabs (somers_d_t[i]));
3014 if (proc->statistics & (1u << CRS_ST_ETA))
3017 double sum_Xr, sum_X2r;
3021 for (sum_Xr = sum_X2r = 0., i = 0; i < xt->n_rows; i++)
3023 sum_Xr += xt->rows[i].f * xt->row_tot[i];
3024 sum_X2r += pow2 (xt->rows[i].f) * xt->row_tot[i];
3026 SX = sum_X2r - pow2 (sum_Xr) / xt->total;
3028 for (SXW = 0., j = 0; j < xt->n_cols; j++)
3032 for (cum = 0., i = 0; i < xt->n_rows; i++)
3034 SXW += pow2 (xt->rows[i].f) * xt->mat[j + i * xt->n_cols];
3035 cum += xt->rows[i].f * xt->mat[j + i * xt->n_cols];
3038 SXW -= cum * cum / xt->col_tot[j];
3040 v[11] = sqrt (1. - SXW / SX);
3044 double sum_Yc, sum_Y2c;
3048 for (sum_Yc = sum_Y2c = 0., i = 0; i < xt->n_cols; i++)
3050 sum_Yc += xt->cols[i].f * xt->col_tot[i];
3051 sum_Y2c += pow2 (xt->cols[i].f) * xt->col_tot[i];
3053 SY = sum_Y2c - sum_Yc * sum_Yc / xt->total;
3055 for (SYW = 0., i = 0; i < xt->n_rows; i++)
3059 for (cum = 0., j = 0; j < xt->n_cols; j++)
3061 SYW += pow2 (xt->cols[j].f) * xt->mat[j + i * xt->n_cols];
3062 cum += xt->cols[j].f * xt->mat[j + i * xt->n_cols];
3065 SYW -= cum * cum / xt->row_tot[i];
3067 v[12] = sqrt (1. - SYW / SY);