Skip to content

Commit 3a173e6

Browse files
crosstab: add categorical vector input support
1 parent 7cf774b commit 3a173e6

1 file changed

Lines changed: 24 additions & 3 deletions

File tree

inst/crosstab.m

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@
2828
## Create a cross-tabulation (contingency table) @var{t} from data vectors.
2929
##
3030
## The inputs @var{x1}, @var{x2}, ... @var{xn} must be vectors of equal length
31-
## with a data type of numeric, logical, char, or string (cell array).
31+
## with a data type of numeric, logical, char, categorical, or cell array of
32+
## strings.
3233
##
3334
## As additional return values @code{crosstab} returns the chi-square statistics
3435
## @var{chisq}, its p-value @var{p} and a cell array @var{labels}, containing
@@ -53,8 +54,8 @@
5354

5455
for i = 1:nargin
5556
vector = varargin{i};
56-
## If char array, convert to numerical vector
57-
if (ischar (vector) || iscellstr (vector))
57+
## Convert char, cellstr, or categorical to indexed numeric vector
58+
if (ischar (vector) || iscellstr (vector) || iscategorical (vector))
5859
try
5960
[vector, gnames] = grp2idx (vector);
6061
catch
@@ -145,3 +146,23 @@
145146
%! y = [1, 2, 3, NaN];
146147
%! t = crosstab (x, y);
147148
%! assert (t, [1, 0, 0; 0, 1, 0]);
149+
150+
## Test categorical input
151+
%!test
152+
%! x = categorical ({'A', 'B', 'A', 'C', 'B'});
153+
%! y = [1, 2, 1, 3, 2];
154+
%! t = crosstab (x, y);
155+
%! assert (size (t), [3, 3]);
156+
%! assert (t(1, 1), 2); # A with 1
157+
%! assert (t(2, 2), 2); # B with 2
158+
%!test
159+
%! x = categorical ({'low', 'med', 'high', 'low', 'med'});
160+
%! y = categorical ({'X', 'Y', 'X', 'Y', 'X'});
161+
%! [t, ~, ~, labels] = crosstab (x, y);
162+
%! assert (size (t), [3, 2]);
163+
%!test
164+
%! ## Test categorical with numeric
165+
%! x = categorical ([10, 20, 10, 30, 20]);
166+
%! y = [1, 2, 1, 3, 2];
167+
%! t = crosstab (x, y);
168+
%! assert (t, [2, 0, 0; 0, 2, 0; 0, 0, 1]);

0 commit comments

Comments
 (0)